php类扩展

时间:2010-11-07 15:29:38

标签: php class extends

嗨,我有一个关于$ this的问题。

class foo {

    function __construct(){

       $this->foo = 'bar';

    }

}

class bar extends foo {

    function __construct() {

        $this->bar = $this->foo;

    }

}

$ob = new foo();
$ob = new bar();
echo $ob->bar;

导致bar ??

我只是因为我认为它会问,但是我的剧本之间似乎没有产生我的想法。

3 个答案:

答案 0 :(得分:10)

引用PHP manual

  

注意:如果子类定义了构造函数,则不会隐式调用父构造函数。为了运行父构造函数,需要在子构造函数中调用 parent :: __ construct()

这意味着在您的示例中bar的构造函数运行时,它不会运行foo的构造函数,因此$this->foo仍未定义。

答案 1 :(得分:5)

PHP parent constructor is not automatically called if you define a child constructor有点奇怪 - 您必须自己调用它。因此,要获得您想要的行为,请执行此操作

class bar extends foo {

    function __construct() {

         parent::__construct();
         $this->bar = $this->foo;

    }

}

答案 2 :(得分:0)

您不会创建foo和bar的实例。创建一个bar实例。

$ob = new bar(); 
echo $ob->bar;

并且正如其他答案所指出的那样,在bar构造函数中调用parent :: __ construct()

相关问题