我有这个问题:我想连接更多的方法,但我需要一个方法(第一个),如果后面有另一个方法,则返回$this,否则返回一个对象。
示例:
$some->create( 'Foo' )->with( 'Bar' );
$some->create( 'Foo' );
在第一个示例中,$some->create()
必须返回$this才能允许串联。在第二种情况下,方法create()
必须返回一个对象。
有没有办法不改变方法的顺序?现在我总是返回$this,然后你可以用另一个函数(例如:$some->create( 'Foo' )->getInfo();
)获得"返回"的对象
谢谢。
方法create()
可能返回任何内容,但没有关于调用方法如何处理它的信息。可能的选项是传递可选参数或使用包装方法。
class Test {
public function create($what, $methodChaining = false)
{
// do stuff, create $object
if ($methodChaining) {
return $this;
}
return $object;
}
public function createAndChain($what)
{
$this->create($what);
return $this;
}
}
$object->create('Foo', true)->with('Bar'); // execute with() on the first $object
$object->createAndChain('Foo')->with('Bar'); // same as above
$object->create('Foo')->with('Bar'); // execute with() from the new Foo-object
此外,代码不知道您是想在第一个对象上执行链式方法,还是在新创建的对象上执行。。