News & UpdatesProgrammingWeb programmingPartnersStore
Book Cover
Buy Now
Projects
Links

PHP Tutorial – 11 – Inheritance

Inheritance enables a class to reuse code from another class. In the example below the Square class inherits from Rectangle through the use of the extends keyword. A class in PHP can only extend from one other class and it will then inherit all non-private members from that class in addition to its own members.

class Rectangle
{
  public $x = 10, $y = 20;
  function __construct($a,$b) 
  { 
    $this->x=$a; 
    $this->y=$b; 
  }
}   
class Square extends Rectangle {}

When creating an instance of Square two arguments must now be specified, because Square has inherited Rectangles constructor.

$s = new Square(5);

The fields inherited from Rectangle can also be accessed from the Square object.

$s->x = 3; $s->y = 5;

Overriding members

To override an inherited member it just needs to be redeclared with the same name. As is shown below, the Square constructor overrides the constructor in Rectangle so a single argument must be used when creating the square.

class Square extends Rectangle
{
  function __construct($a) 
  { 
    $this->x=$a; 
    $this->y=$a; 
  }
}

The constructor of Rectangle will now no longer be called when the Square object is created. In order to call the parent’s constructor from the child class the parent keyword and a double colon must be prepended to the call. The double colon (::) is known as the scope resolution operator and is used to access members of a class. This is different from the single arrow operator (->) which accesses members belonging to an instance of a class.

class Square extends Rectangle
{
  function __construct($a) 
  { 
    parent::__construct($a,$a); 
  }
}

The parent keyword is an alias for the parent’s class name, which could just as well have been used instead.

class Square extends Rectangle
{
  function __construct($a) 
  { 
    Rectangle::__construct($a,$a); 
  }
}

In PHP, this notation can be used to access overridden members that are any number of levels deep in the inheritance hierarchy.

Preventing inheritance

To stop a child class from overriding a method it can be declared as final. A class itself can also be declared as final to prevent any class from extending it.

final class Square extends Rectangle
{
  final function __construct($a) 
  { 
    Rectangle::__construct($a,$a); 
  }
}

Instanceof operator

When using objects it’s good to know about the instanceof operator. This operator will return true if the left side object is an instance of, or inherits from, the right side class.

$s = new Square(5);
$a = $s instanceof Square    // true
$b = $s instanceof Rectangle // true

If you like this tutorial please +1 it:


One Response

April 11th, 2011 at 11:12  

Great tihnikgn! That really breaks the mold!

Leave a Reply