php 类扩展

发布于 2024-09-30 20:38:10 字数 402 浏览 0 评论 0原文

您好,我有一个关于 $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??

我只是因为我认为会这样而问,但我的脚本的一部分似乎并没有达到我的想法。

Hi I have a question regarding $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??

I only ask due to I thought it would but apart of my script does not seem to result in what i thought.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

轮廓§ 2024-10-07 20:38:10

引用 PHP 手册 :

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

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

To quote the PHP manual:

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.

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.

枕花眠 2024-10-07 20:38:10

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

class bar extends foo {

    function __construct() {

         parent::__construct();
         $this->bar = $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. Thus, to get the behaviour you intend, do this

class bar extends foo {

    function __construct() {

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

    }

}
峩卟喜欢 2024-10-07 20:38:10

您不会同时创建 foo 和 bar 的实例。创建 bar 的单个实例。

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

正如其他答案所指出的,在 bar 构造函数中调用parent::__construct()

You don't create an instance of both foo and bar. Create a single instance of bar.

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

and as other answers have pointed out, call parent::__construct() within your bar constructor

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文