Categories
PHP

PHP extending classes, class inheritance

Sample code:

class ChildClass extends ClassName { }

In this case ClassName is the parent, or superclass, and ChildClass inherits all of its properties, plus it is able to add its own.

When you use inheritance, you are responsible to passing arguments back to your parent class. Take the following example (check how parent::__construct() takes care of that for you):

function __construct(  $title, $firstName,
                           $mainName, $price, $numPages ) {
        parent::__construct(  $title, $firstName,
                              $mainName, $price );
        $this->numPages = $numPages;
    }

It is actually better to use parent::__construct() instead of real_parent_class_name_here::__construct(), just in case the parent changes later you don’t have to worry about changing code in the child class.