Reputation: 2548
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?
Upvotes: 1
Views: 162
Reputation: 577
Of course when you extend a class, the subclass inherits all of the public and protected methods from the parent class.
Upvotes: 0
Reputation: 29856
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
Upvotes: 2
Reputation: 8941
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.
Upvotes: 5
Reputation: 85784
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();
}
Upvotes: 1