views:

39

answers:

4

If I have the following class:

class foo {
    function __construct() {
        // Some code
    }
}

And then use inheritance to create:

class bar extends foo {
    // Some code
}

When I instantiate class 'bar', will it automatically execute the __construct method from 'foo' or do I need to do something else to get that method to execute?

+1  A: 

The __construct will carry over, yes.

The issue comes when you want to add something to that function, which is when the parent class comes in handy.

class bar extends foo {
    $this->doSomethingElse();
    parent::__construct();
}
Matchu
+5  A: 

From the manual:

Note: Parent constructors are not called implicitly if the child class defines a constructor.

While the documentation doesn't state it explicitly, the inverse of this sentence is also true, i.e., parent constructors are called implicitly if the child class does not define a constructor. Therefore, in your example, instantiating bar would call foo::__construct automatically.

bcat
+2  A: 

it works, the constructer from the parent class will be inherited. if you define a new constructor in the instaciated class, it will override the constructor function of the parent class. if you still want to execute the parent constructer you should include

parent::__construct(); 

in the constructer of thje isntanciated class

Joe Hopfgartner
A: 

Of course when you extend a class, the subclass inherits all of the public and protected methods from the parent class.

aromawebdesign.com