php类扩展

Phi*_*son 6 php extends class

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

class foo {

    function __construct(){

       $this->foo = 'bar';

    }

}

class bar extends foo {

    function __construct() {

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

    }

}
Run Code Online (Sandbox Code Playgroud)

$ob = new foo();
$ob = new bar();
echo $ob->bar;
Run Code Online (Sandbox Code Playgroud)

结果bar??

我只是问,因为我认为它会,但我的脚本的一部分似乎没有导致我的想法.

Vil*_*lx- 10

引用PHP手册:

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

这意味着在你的例子中bar运行构造函数时,它不运行构造函数foo,因此$this->foo仍然是未定义的.


Pau*_*xon 5

PHP有点奇怪,如果定义子构造函数,则不会自动调用父构造函数 - 您必须自己调用它.因此,要获得您想要的行为,请执行此操作

class bar extends foo {

    function __construct() {

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

    }

}
Run Code Online (Sandbox Code Playgroud)