Alexander Trauzzi
Alexander Trauzzi

Reputation: 7405

PHP Method Chains - Reflecting?

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

Upvotes: 4

Views: 651

Answers (5)

Brenton Alker
Brenton Alker

Reputation: 9082

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');

Upvotes: 2

Mario
Mario

Reputation: 1525

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.

Upvotes: 0

Lior Cohen
Lior Cohen

Reputation: 9055

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.

Upvotes: 1

grantwparks
grantwparks

Reputation: 1153

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.

Upvotes: 1

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53606

$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.

Upvotes: 0

Related Questions