1

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
  • 6
    Have you tried it? :) Commented Aug 24, 2010 at 0:36

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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();
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.