Parent constructors

Take a look at this code:

class poodle extends dog {
    public function bark() {
        print "Yip!\n";
    }
    
    public function __construct($DogName) {
        print "Creating a poodle\n";
    }
}

If you replace the original poodle definition with this new one and try running the script again, you will get the error "Trying to get property of non-object" on the line where we have print $poppy->DogTag->Words. The reason for this is because DogTag is only defined as being an instance of our dogtag object in the dog class constructor, and, as PHP will only ever call one constructor for us, the dog class constructor is not called because PHP finds the poodle constructor first.

The fact that PHP always calls the "nearest" constructor, that is if there is no child constructor it will call the parent constructor and not the grandparent constructor, means that we need to call the parent constructor ourselves. We can do this by using the special function call parent::__construct(). The "parent" part means "get the parent of this object, and use it", and the __construct() part means "call the construct function", of course. So the whole line means "get the parent of this object then call its constructor".

As you can see, the call to the parent's __construct() is just a normal function call, and the dog constructor needs a dog name as its parameter. So, to make the poodle class work properly, we would need the following:

class poodle extends dog {
    public function bark() {
        print "Yip!\n";
    }
    
    public function __construct($DogName) {
        parent::__construct($DogName);
        print "Creating a poodle\n";
    }
}

Try running that - you should get output like to this:

Creating Poppy
Creating a poodle
My name is Poppy. If you find me, please call 555-1234

Note that "Creating Poppy" is output before "Creating a poodle", which might seem backwards, but it makes sense given that we call the dog constructor before we do any poodle code. It is always best to call parent::__construct() first from the constructor of a child class in order to make sure all the parent's variables are set up correctly before you try and set up the new stuff.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Destructors >>

Previous chapter: Constructors and destructors

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.