What happens if you do not explicitly call the parent constructor in PHP?

advertisements

I was wondering why we have to explicitly call parent constructor in PHP? What happen if, let's say, we forget to call the parent constructor in the derived class?

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

So do we have to explicitly call its parent constructor? What are the consequences if we forget to do so?

Thanks in advance. Any kinds of help will be appreciated :)


It depends on your code. In it's simpliest nothing happens if you dont call parent constructor, but if your parent constructor does something initializing for parent class, all that is left out. Consider, and play with this:

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

It's easy to see that if you run this, it prints out 5 (among other dump). But if you comment class Y parent call parent::__construct($a);, you get 2. That is the consequence in this case.