php,我需要来自父对象的子对象,如何?

发布于 2024-12-15 04:20:24 字数 235 浏览 3 评论 0原文

class Parent
{
 public function exec()
 {
  // here I need the child object!
 }
}

class Child extends Parent
{
 public function exec()
 {
  // something
  parent::exec();
 }
}

如您所见,我需要父对象的子对象。我怎样才能达到它?

class Parent
{
 public function exec()
 {
  // here I need the child object!
 }
}

class Child extends Parent
{
 public function exec()
 {
  // something
  parent::exec();
 }
}

as you can see, I need the child object from the parent. How can I reach it?

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

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

发布评论

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

评论(1

放手` 2024-12-22 04:20:24

您可以将孩子作为参数传递:

class ParentClass
{
    public function exec( $child )
    {
        echo 'Parent exec';
        $child->foo();
    }
}

class Child extends ParentClass
{
    public function exec()
    {
        parent::exec( $this );
    }

    public function foo() 
    {
        echo 'Child foo';
    }
}

但这很少需要,因此可能有更好的方法 你想要做什么

You can pass the child as an argument:

class ParentClass
{
    public function exec( $child )
    {
        echo 'Parent exec';
        $child->foo();
    }
}

class Child extends ParentClass
{
    public function exec()
    {
        parent::exec( $this );
    }

    public function foo() 
    {
        echo 'Child foo';
    }
}

This is rarely needed though, so there might be a better way to do what you're trying to do.

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