是否可以通过一系列方法调用来确定您在调用链中的哪个位置?至少,是否有可能辨别一个方法是否是链中的最后一个调用?
$instance->method1()->method2()->method3()->method4()
是否可以使用返回对象实例的属性来做同样的事情?
$instances->property1->property2->property3->property4
是否可以通过一系列方法调用来确定您在调用链中的哪个位置?至少,是否有可能辨别一个方法是否是链中的最后一个调用?
$instance->method1()->method2()->method3()->method4()
是否可以使用返回对象实例的属性来做同样的事情?
$instances->property1->property2->property3->property4
如果您调用的所有方法都返回相同的对象以创建流畅的接口(而不是将不同的对象链接在一起),那么在对象本身中记录方法调用应该是相当简单的。
例如:
class Eg {
protected $_callStack = array();
public function f1()
{
$this->_callStack[] = __METHOD__;
// other work
}
public function f2()
{
$this->_callStack[] = __METHOD__;
// other work
}
public function getCallStack()
{
return $this->_callStack;
}
}
然后像这样链接调用
$a = new Eg;
$a->f1()->f2()->f1();
会像这样离开调用堆栈:array('f1', 'f2', 'f1');
For chained methods, you could use PHP5's overloading methods (__call in this case).
I don't see any reason why you would want to track chained properties, but if you insist on doing this, you could use the __get overloading method on your classes to add the desired functionality.
Please let me know if you couldn't figure out how to use the suggestions above.
debug_backtrace() 对于“流式接口”(图示的“链接”的正确名称)的使用是不正确的,因为每个方法都会在调用下一个方法之前返回。
我认为没有一种可行的方法让一个类知道它的最后一次方法调用是什么时候进行的。我认为你需要某种 ->execute(); 函数调用在链的末尾。
此外,在我看来,启用这样的功能可能会使代码过于神奇,让用户感到惊讶和/或出现错误症状。
$instances->property1->property2->property3->property4->method();
或者
$instances->property1->property2->property3->property4=some_value
至于第一个问题:并非不添加一些代码来跟踪您在链中的位置。