Kisaragi
Kisaragi

Reputation: 2218

Why do I type parent::__construct?

Each time I go to declare an extended class,

Class cookies extends Food{
    public function __construct()
    {
        parent::__construct();
    }
}

Why am I using parent::__construct()?

Is this for inheritance? Does merely extending the class not inherit it's properties?

Upvotes: 1

Views: 2681

Answers (2)

CodeGodie
CodeGodie

Reputation: 12132

Its real simple. If you plan your child's class to have a __construct, then you need to decide, "will I also want my parent's __construct to be inherited?" if so, then you need to use parent::__construct().

Take this example into consideration:

class Actions {

    function __construct() {
        echo "I can do even more actions and.. ";
    }

    function jump() {
        return "hop hop";
    }

    function eat() {
        return "munch munch";
    }
}

class Humans extends Actions {

    function __construct() { //this will overwrite the parents construct
        echo "I am a human and ...";
    }


    function talk() {
        return "I can talk";
    }

}

class Dogs extends Actions {

    function __construct() { //this will NOT overwrite the parents construct
        parent::__construct();
        echo "I am a dog and ...";
    }


    function bark() {
        return "I can bark";
    }

}

If we run a Human() function, we will get the following:

$human = new Humans();
var_dump($human->talk());

/*
RESULT:

I am a human and ...
string 'I can talk' (length=10)
*/

However, if we run a Dogs() function, we will get the following:

$dogs = new Dogs();
var_dump($dogs->bark());

/*
RESULT:
I can do even more actions and.. I am a dog and ...
string 'I can bark' (length=10)
*/

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212452

If that's the sole content of your child class constructor, then you don't need to define the child constructor at all, and it will simply run the parent constructor.

If you do create a child class with a constructor, then that child constructor will run instead of the parent class constructor (even if it's just an empty body); so if you need to run the parent class's constructor as well then you need to call it explicitly by using parent::__construct()

Upvotes: 8

Related Questions