PHP Method Chains - Reflecting?

戏子无情 提交于 2019-12-10 15:39:37

问题


Is it possible to reflect upon a chain of method calls to determine at what point you are in the chain of calls? At the very least, is it possible to discern whether a method is the last call in the chain?

$instance->method1()->method2()->method3()->method4()

Is it possible to do the same using properties that return instances of objects?

$instances->property1->property2->property3->property4

回答1:


If all the methods you're calling are returning the same object to create the fluent interface (as opposed to chaining different objects together), it should be fairly trivial to record the method calls in the object itself.

eg:

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;
    }
}

Then chaining the calls like

$a = new Eg;
$a->f1()->f2()->f1();

would leave the call stack like: array('f1', 'f2', 'f1');




回答2:


debug_backtrace() is not going to be correct regarding the use of "fluent interfaces" (the proper name for the "chaining" illustrated), because each method returns, before the next one is called.




回答3:


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.




回答4:


$instances->property1->property2->property3->property4->method();

OR

$instances->property1->property2->property3->property4=some_value

As for the first question: not without adding some code to track where you are in the chain.




回答5:


I don't think there's a feasible way for a class to know when it's last method call was made. I think you'd need some kind of ->execute(); function call at the end of the chain.

Besides, enabling such functionality in my opinion would probably make the code too magical and surprise users and/or have buggy symptoms.



来源:https://stackoverflow.com/questions/1178487/php-method-chains-reflecting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!