PHP Tutorial - PHP Class Inheritance






PHP Class Inheritance

With inheritance we can create child classes that are based on the parent class.

A child class inherits all the properties and methods of its parent, and it can also add additional properties and methods.

To create a child class that ' s based on a parent class, you use the extends keyword, as follows:

<?PHP
class Shape { 
   // (General Shape properties and methods here) 
} 
              
class Circle extends Shape { 
   // (Circle-specific properties and methods here) 
}     
?>

To extend the Dog class we can use extends keyword.

<?PHP
class Dog {
    public function bark() {
       print "Woof!\n";
    }
}

class Puppy extends Dog {
   
}
?>




Example

The following code shows how to call current class with self.

<?php
  class Animal
  {
    public $blood;
    public $name;

    public function __construct($blood, $name=NULL)
    {
      $this->blood = $blood;
      if($name)
      {
        $this->name = $name;
      }
    }
  }

  class Mammal extends Animal
  {
    public $furColor;
    public $legs;

    function __construct($furColor, $legs, $name=NULL)
    {
      parent::__construct("warm", $name);
      $this->furColor = $furColor;
      $this->legs = $legs;
    }
  }

  class Dog extends Mammal
  {
    function __construct($furColor, $name)
    {
      parent::__construct($furColor, 4, $name);
      self::bark();
    }

    function bark()
    {
      print("$this->name says 'woof!'");
    }
  }

  $d = new Dog("Black and Tan", "Angus");
?>


The code above generates the following result.





Example 2

The following code shows how to call parent constructor.


<?php

class Calculator {
  protected $_val1, $_val2;

  public function __construct( $val1, $val2 ) {
    $this->_val1 = $val1;
    $this->_val2 = $val2;
  }

  public function add() {
    return $this->_val1 + $this->_val2;
  }

  public function subtract() {
    return $this->_val1 - $this->_val2;
  }

  public function multiply() {
    return $this->_val1 * $this->_val2;
  }

  public function divide() {
    return $this->_val1 / $this->_val2;
  }
}

class CalcAdvanced extends Calculator {
  private static $_allowedFunctions = array( "pow" => 2, "sqrt" => 1, "exp" => 1 );

  public function __construct( $val1, $val2=null ) {
    parent::__construct( $val1, $val2 );
  }

  public function __call( $methodName, $arguments ) {
    if ( in_array( $methodName, array_keys( CalcAdvanced::$_allowedFunctions ) ) ) {
      $functionArguments = array( $this->_val1 );
      if ( CalcAdvanced::$_allowedFunctions[$methodName] == 2 ) array_push( $functionArguments, $this->_val2 );
      return call_user_func_array( $methodName, $functionArguments );
    } else {
      die ( "<p>Method 'CalcAdvanced::$methodName' doesn't exist</p>" );
    }
  }
}
$ca = new CalcAdvanced( 3, 4 );
echo "<p>3 + 4 = " . $ca->add() . "</p>";
echo "<p>3 - 4 = " . $ca->subtract() . "</p>";
echo "<p>3 * 4 = " . $ca->multiply() . "</p>";
echo "<p>3 / 4 = " . $ca->divide() . "</p>";
echo "<p>pow( 3, 4 ) = " . $ca->pow() . "</p>";
echo "<p>sqrt( 3 ) = " . $ca->sqrt() . "</p>";
echo "<p>exp( 3 ) = " . $ca->exp() . "</p>";

?>


The code above generates the following result.

PHP Overriding Methods

To create a child class whose methods are different from the corresponding methods in the parent class by overriding a parent class's method in the child class.

To do this, simply create a method with the same name in the child class. Then, when that method name is called for an object of the child class, the child class's method is run instead of the parent class's method:

<?PHP
class ParentClass { 
  public function someMethod() { 
    // (do stuff here) 
  } 
} 
     
class ChildClass extends ParentClass { 
  public function someMethod() { 
    // This method is called instead for ChildClass objects 
  } 
} 

$parentObj = new ParentClass; 
$parentObj->someMethod();  // Calls ParentClass::someMethod() 
$childObj = new ChildClass; 
$childObj->someMethod();   // Calls ChildClass::someMethod()  
?>

PHP allows us to redefine methods in subclasses. This is done by redefining the method inside the child class:

<?PHP
class Dog {
    public function bark() {
       print "Dog";
    }
}

class Puppy extends Dog {
   public function bark() {
      print "Puppy";
   }
}
?>

Preserving the Functionality of the Parent Class

To call an overridden method, you write parent:: before the method name:

parent::someMethod();
<?php 
    class Fruit { 
      public function peel() { 
        echo "peeling the fruit.\n"; 
      } 
      public function slice() { 
        echo "slicing the fruit.\n"; 
      } 
            
      public function eat() { 
        echo "eating the fruit. \n"; 
      } 
            
      public function consume() { 
        $this-> peel(); 
        $this-> slice(); 
        $this-> eat(); 
      } 
    } 
    class Banana extends Fruit { 
        public function consume() { 
          echo " < p > I'm breaking off a banana... < /p > "; 
          parent::consume(); 
        } 
     } 

     $apple = new Fruit; 
     $apple->consume(); 
                 
     $banana = new Banana; 
     $banana->consume();   
                     
?>  

The code above generates the following result.

PHP final Classes and Methods

To lock down a class so that it can't be inherited from. Or to lock down one or more methods inside a class so that they can't be overridden in a child class.

By doing this, you know that your class or methods within your class will always behave in exactly the same way.

You can add the keyword final before a class or method definition to lock down that class or method.

Here's how to create a final class:

final class MyClass { 

} 

Here's how you make a final method:

class ParentClass { 
   public final function myMethod() { 
            echo "A method"; 
   } 
}