为什么父类的受保护变量为空


Why a protected variable of parent class come empty?

我在Father类中得到了一个受保护的变量,该变量的内容在Father类中会发生变化,但我需要在子类中使用该变量,即:

class Father {
   protected $body;
   function __construct(){
       $this->body = 'test';
    }
}
class Child extends Father{
    function __construct(){
       echo $this->body;
    }
}
$c = new Father();
$d = new Child();

为什么变量body为空?如果我将其声明为静态的,那么如果我想在子类中访问和修改这些变量,我是否应该将所有变量声明为静态?

您必须调用父构造函数。

class Father {
   protected $body;
   function __construct(){
       $this->body = 'test';
   }
}
class Child extends Father {
   function __construct(){
       parent::__construct();
       echo $this->body;
   }
}
$c = new Father();
$d = new Child();

参考:http://php.net/manual/en/language.oop5.decon.php

这是因为您正在重写构造函数。您还必须调用父级的构造函数更多信息

class Child extends Father {
    function __construct() {
        parent::__construct();
        echo $this->body;
    }
}