Why does my PHP child class not become public and protected by the parent?

advertisements

I'm having brainfreeze, and I suspect this one is really simple. Consider this code, with two classes:

<?php
class myparentclass {
    protected $vara;
    private $varb;
    public $varc;
    public $_childclass;

    function __construct() {
        $this->vara = "foo";
        $this->varb = "bar";
        $this->varc = ":(";
        $this->_childclass = new mychildclass;
    }
}

class mychildclass extends myparentclass {
    function __construct() {
        print_r ($this);
    }
}

print "<pre>";
$foo = new myparentclass();

The output is:

mychildclass Object
(
    [vara:protected] =>
    [varb:private] =>
    [varc] =>
    [_childclass] =>
)

I know $varb shouldn't be set, but what about the others?


If you define a new __construct() in the child class as you've done to print vars out, you need to explicitly call the parent's constructor too. If you did not define any __construct() in the child class, it would directly inherit the parent's and all those properties would have been set.

class mychildclass extends myparentclass {
  function __construct() {
    // The parent constructor
    parent::__construct();
    print_r ($this);
  }
}