问题描述:

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?

网友答案:

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.

网友答案:

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

网友答案:

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();
}
网友答案:

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

相关阅读:
Top