PHP:类扩展

时间:2016-02-23 11:36:43

标签: php

我已经制作了一些示例代码来解释我的问题:

class Core {
   public $test = null;
   public function __construct(){
       $this->test = "hi";
   }
}

$data = new Core;

class Extension extends Core {
    public function __construct(){
        $this->test = "hello";
    }
}

$data->ext = new Extension;

echo $data->test . "<br />";
echo $data->ext->test;

输出为:

  

你好你好

我的问题很难解释,但我只是想知道是否有办法覆盖子类中父类的$ test变量,所以:

echo $this->test;会输出“hello”,因为它在子类中发生了变化。

有没有办法做到这一点,或者孩子不能访问/更改父变量?

1 个答案:

答案 0 :(得分:1)

为您的用例使用static属性。

点击http://php.net/manual/en/language.oop5.static.php,第二个示例可以帮助您

相关问题