Php 是否可以使用“中的函数”;“假父母”;类,将当前类作为属性?

Php 是否可以使用“中的函数”;“假父母”;类,将当前类作为属性?,php,class,oop,Php,Class,Oop,下面的示例定义了一个foo类,它构造了一个bar类,并将其存储为属性$foo->bar。在bar类中,是否可以引用'false'父类并使用其函数 class bar { public function test_false_parent() { //Is it possible to access foo->display() from here {unknown code}::display(); } } class fo

下面的示例定义了一个foo类,它构造了一个bar类,并将其存储为属性
$foo->bar
。在bar类中,是否可以引用'false'父类并使用其函数

class bar
{
    public function test_false_parent()
    {
            //Is it possible to access foo->display() from here
        {unknown code}::display();
    }
}

class foo
{
    public $bar;

    public function __construct()
    {
        $this->bar = new bar;
    }

    public function display()
    {
        echo "in";
    }
}

$foo = new foo;

$foo->bar->test_false_parent();
//Equivalent to $foo->display();

没有反向引用:

class bar
{
    protected $foo;

    public function __construct(foo $foo)
    {
        $this->foo = $foo;
    }

    public function test_false_parent()
    {
        $this->foo->display();
    }
}

class foo
{
    public $bar;

    public function __construct()
    {
        $this->bar = new bar($this);
    }

    public function display()
    {
        echo "in";
    }
}

$foo = new foo;

$foo->bar->test_false_parent();

没有反向引用:

class bar
{
    protected $foo;

    public function __construct(foo $foo)
    {
        $this->foo = $foo;
    }

    public function test_false_parent()
    {
        $this->foo->display();
    }
}

class foo
{
    public $bar;

    public function __construct()
    {
        $this->bar = new bar($this);
    }

    public function display()
    {
        echo "in";
    }
}

$foo = new foo;

$foo->bar->test_false_parent();

很棒的解决方案,因为你可以做
$foo->bar->foo->bar->foo->bar->foo->bar->test\u false\u parent()
:)哈,只是有同样的想法。谢谢!我不确定我是否会使用这种方法,但很高兴知道这是一种可能性。很棒的解决方案,因为你可以做
$foo->bar->foo->bar->foo->bar->foo->bar->test\u false\u parent()
:)哈,也有同样的想法。谢谢!我不确定我是否会使用这种方法,但很高兴知道这是一种可能性。