简体   繁体   English

php类扩展

[英]php classes extend

Hi I have a question regarding $this. 嗨,我有一个关于$ this的问题。

class foo {

    function __construct(){

       $this->foo = 'bar';

    }

}

class bar extends foo {

    function __construct() {

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

    }

}

would

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

result in bar ?? 结果bar

I only ask due to I thought it would but apart of my script does not seem to result in what i thought. 我只问是因为我以为会,但是我的脚本的一部分似乎并没有导致我的想法。

To quote the PHP manual : 引用PHP手册

Note: Parent constructors are not called implicitly if the child class defines a constructor. 注意:如果子类定义了构造函数,则不会隐式调用父构造函数。 In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. 为了运行父构造函数,需要在子构造函数内调用parent :: __ construct()

This means that in your example when the constructor of bar runs, it doesn't run the constructor of foo , so $this->foo is still undefined. 这意味着在您的示例中,当bar的构造函数运行时,它没有运行foo的构造函数,因此$this->foo仍未定义。

PHP is a little odd in that a parent constructor is not automatically called if you define a child constructor - you must call it yourself. PHP有点奇怪, 如果您定义子构造函数,则不会自动调用父构造函数 -必须自己调用它。 Thus, to get the behaviour you intend, do this 因此,要获得您想要的行为,请执行此操作

class bar extends foo {

    function __construct() {

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

    }

}

You don't create an instance of both foo and bar. 您不会同时创建foo和bar的实例。 Create a single instance of bar. 创建bar的单个实例。

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

and as other answers have pointed out, call parent::__construct() within your bar constructor 正如其他答案指出的那样,在bar构造函数中调用parent :: __ construct()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM