G
G
Grigory Vasilkov2019-09-19 14:01:42
PHP
Grigory Vasilkov, 2019-09-19 14:01:42

Why can a constructor signature be overridden? What is this convention for?

The code below will work for the constructor.
For any other method, no, and it's reasonable for a child to implement the parent's method in a different way rather than doing the complete opposite

class Car
{
  protected $engine;
  protected $wheels;
  public function __construct(Engine $engine, Wheels $wheels)
  {
    $this->engine = $engine;
    $this->wheels = $wheels;
  }

  public function engineStart()
  {
    $this->engine->start();
  }
}
class Bmw extends Car
{
  public function __construct(Wheels $wheels) // ! damn, its OK !
  {
    $this->wheels = $wheels;
  }
}

(new Bmw)->engineStart(); // Trying to call method on null

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
green_goo, 2019-09-19
@gzhegow

The parent cannot know what might be needed to instantiate the child.
Not ok. There is no call to the parent's constructor in the constructor of the child

A
Alexey Nikolaev, 2019-09-19
@Heian

Well, in general, it is on the conscience of the developer, in this case, compliance with the Liskov substitution. Concerning the constructor, it is often redefined to add a parameter or additional initialization, but the parent constructor must be called with the correct parameters passed to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question