PHP Method Chains - Reflection?

Can you think of a chain of method calls to determine at what point you are in a chain of calls? At least is it possible to determine if a method is the last call in a 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 
+4
source share
5 answers

If all the methods you call return the same object to create a free interface (as opposed to chaining different objects together), it should be pretty trivial to record 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 a chain of calls such as

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

leaves the call stack as follows: array ('f1', 'f2', 'f1');

+2
source

For chained methods, you can use PHP5 overload methods (in this case __call).

I don’t see the reasons why you want to track attached properties, but if you insist on it, you can use the __get overload method on your classes to add the necessary functions.

Please let me know if you cannot figure out how to use the above suggestions.

+1
source

debug_backtrace () will not be correct regarding the use of "runaway interfaces" (displaying its own name for the "chain"), since each method returns until the next call.

+1
source
 $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.

0
source

I don't think there is an acceptable way for a class to know when the last method call was made. I think you need something -> execute (); function call at the end of the chain.

In addition, the inclusion of such functions in my opinion would probably make the code too magical and unexpected for the user and / or have glitchy symptoms.

0
source

All Articles