John
John

Reputation: 1665

PHP OOP class construct inheritance

I am trying to understand one PHP OOP concept, lets say i have two classes A and B. B extends A there fore A is Base/Parent class. If class A has a __construct class B will automatically inherit it...?

Example:

class Car 
{

    public $model;
    public $price;

    public function __construct()
    {
        $this->model = 'BMW';
        $this->price = '29,00,00';
    }

}

class Engine extends Car
{
    parent::__construct();
}

By parent::__construct(); class Engine will execute Car __construct(); automatically?

But I always though if I inherit from parent class the __construct will be executed automatically anyway why would I add this parent::__construct()?

Upvotes: 0

Views: 264

Answers (2)

deceze
deceze

Reputation: 522597

When one class extends another, it inherits all its methods. Yes, that includes the constructor. You can simply do class Engine extends Car {}, and Engine will have a constructor and all other properties and methods defined in Car (unless they're private, which we'll ignore here).

If you define a method of the same name as already exists in Car in Engine, you're overriding that method implementation. That's exactly what it sounds like: instead of Car's implementation, Engine's method is called.

why would I add this parent::__construct()?

If you're overriding a method, yet you also want to call the parent's implementation. E.g.:

class Engine extends Car {
    public function __construct() {
        parent::__construct();
        echo 'Something extra';
    }
}

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212522

Overriding a constructor in a child class is exactly that, overriding... you're setting a new constructor for the child to replace the parent constructor because you want it to do something different, and generally you won't want it to call the parent constructor as well..... that's why you need to explicitly call the parent constructor from the child constructor if you want them both to be executed.

If you don't create a child constructor, then you're not overriding the parent constructor, so the parent constructor will then be executed

Upvotes: 0

Related Questions