如何在课堂内部进行链接?

时间:2014-07-21 19:15:08

标签: php fluent-interface

我想知道我们是否可以内部链接'在一个班级本身?例如,我有这两个类,

头等,

class Object1
{
    public $item;
    public $obj2;

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

    public function chain1()
    {
        $this->item = 'Chain1 ';

        return $this; 
    }

    public function chain2()
    {

        //$this->item = $this->obj2->chain3(); // works ok.
        $this->item = $this->obj2->chain3()->chain1(); // how to chain yourself?

        return $this;
    }
}

第二课,

class Object2
{
    public $item;
    public function chain3()
    {
        $this->item = 'Chain 3 ';
        return $this; 
    }

    public function chain4()
    {
        $this->item = 'Chain4 ';
        return $this;
    }
}

$obj1 = new Object1();
print_r($obj1->chain2()->item);

误差,

atal error: Call to undefined method Object2::chain1() in C:...

我需要在类chain1()中链接Ojbect1()

$this->item = $this->obj2->chain3()->chain1(); 

有可能吗?

1 个答案:

答案 0 :(得分:1)

您可以通过从中返回$this链接方法:

class foo
{
    public $foo;
    public function yayThisChains()
    {
        return $this->chain()->chain2()->doIt();
    }
    private function doIt()
    {
        $this->foo = 'bar';
        return $this;
    }
    private function chain2() { return $this; }
    private function chain() { return $this; }
}

$foo = new foo();
echo $foo->yayThisChains()->foo;

问题是你试图使用相同的$this链接两个不同的对象。您可以扩展您的课程,以便$this引用相同的课程,而不是通过构造函数在object2中构建object1

class Object2 extends Object1