PHP Constructors, Cascading Them

Keywords: object oriented programming, PHP, constructors

I was having a hard time finding the right way to cascade constructors in PHP. All the examples I found didn't really discuss extending a base class, or if they did, tended to focus on how functions are inherited.

They didn't address the necessity of cascading a call to the parent class constructor. Why does this matter?

The constructor initializes the object. A subclass should only initialize it's own properties, and let the parent class initialize its properties. Each subclass should call the parent class constructor.

The question I had was: "what's the proper syntax?" Three came to mind:

$this->Parent();
parent::Parent();
$parent->Parent();

The answer is: the first two will work. The third will not work.

In PHP 5, there's a new name for the constructor: __constructor();

This allows us to cascade the call like this: parent::__constructor();

That is generic, and will continue to work if you change the base class name. You don't normally change the base class name, but, it might happen. You might cut and paste the code into another class, as well.

I was using PHP 4, so, my constructors are still named after the class.

Anyway, I found no good examples, so I experimented. The experimental code is below. I hope you find it instructive.


<?php
class Base {
    var $base='unset';
    var $xx = 'foo';

function Base( $x )
    {
    $this->base = $x;
    }
}

class More extends Base {
    var $more='moreunset';

	function More( $x )
    {
        $this->more = $x;
        parent::Base( $x );
    }

}

$a = new More( 'text' );
?>

<h1><?= $a->more ?></h1>
<h1><?= $a->base ?></h1>
<h1><?= $a->xx ?></h1>

This example returns "text text foo", demonstrating that 
cascading the call to the contructor worked.