开发者

Why is my PHP child class not getting public and protected vars from the parent?

开发者 https://www.devze.com 2023-03-08 02:35 出处:网络
I\'m having brainfreeze, and I suspect this one is really simple. Consider this code, with two classes:

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 $v开发者_如何学Goarc;
    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);
  }
}


You have to call the parent class constructor inside the child class constructor.

function __construct() {
        parent::__construct();
        print_r ($this);
    }


If you re-define the constructor in your child class, you have to call the parent constructor.

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

Should work fine.


If the child class has it's own constructor, you must explicitly call the parent constructor from within it (if you want it called):

parent::__construct();


Your parent constructor is never executed by the child. Modify mychildclass like this:

function __construct() {
    parent::__construct();
    print_r ($this);
}


You're overriding the parent class' constructor with the constructor in your parent class. You can call the parent's constructor from your child class with parent::__construct();

However the last line of the constructor of myparentclass calls the constructor of mychildclass which in turn calls the parent constructor, et cetera. Did you mean to achieve this?

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

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

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

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

精彩评论

暂无评论...
验证码 换一张
取 消