What happens if you don't call the parent constructor explicitly in PHP?

I was wondering why should we explicitly call the parent constructor in PHP? What happens if, for example, we forget to call the parent constructor in a derived class?

I thought that the derived class would not have access to the properties or method of its parent class, but after I try not to call the parent constructor, it seems that the child class still gets access to its parent public / protected member.

So, should we explicitly call its parent constructor? What are the consequences if we forget to do this?

Thanks in advance. Any kind of help would be appreciated :)

+5
source share
3 answers

. , , - , . , :

<?php

class X {
    private $_a;

    public function __construct($a) {
        echo 'X::construct ';
        $this->_a = $a;
    }

    public function getA() {
        return $this->_a;
    }
}

class Y extends X {
    private $_b;

    public function __construct($a,$b) {
        echo 'Y::construct ';
        parent::__construct($a);
        $this->_b = $b;
    }

    public function getAB() {
        return $this->_b + $this->getA();
    }
}

$n = new Y(3,2);
echo $n->getAB();

, , 5 ( ). class Y parent::__construct($a);, 2. .

+4

, . , , , .

, , , , . . , , .

, . , ? , . , , , ? , , .

+3

, . , , . / - , , .

Generally, a good solution is to always add a call to the parent constructor, even if nothing happens there (this may change in the future). The only reason not to accept this call is when you need to override the actions that are performed in the constructor. This is a feature that adds more flexibility than you, for example. in Java, where a required parent constructor is required.

+1
source

All Articles