Search code examples
phpmethod-chaining

PHP: The name of the previous method in chain


I am method chaining in PHP, something like this:

$c = new someClass();

$c->blackMethod()->colourMethod();
$c->whiteMethod()->colourMethod();

Is there any way the colourMethod() can know if it was called after the blackMethod() or whiteMethod()? In other words, is there a way of getting the name of the previously called method in a chain of methods?

Something like this:

$c->blackMethod()->colourMethod();
//output: "The colour is black";

$c->whiteMethod()->colourMethod();
//output: "The colour is white";

I understand that chaining is only shorthand for calling multiple methods from the same class, but I was hoping there is a way to link the chains together somehow.

I have tried debug_backtrace() and

$e = new Exception();
$trace = $e->getTrace();

but they only give class names or the name of the method that called the colourMethod (which is $c), not the method that was called before it.


Solution

  • A good and more general way to get a track of the previously called method is to use a private or protected property to keep track of the actual method using the constante __FUNCTION__ or __METHOD__
    example:

       class colorchanger
        {
        protected prevMethod;
        public function black() 
        { 
        /*
        your routine
        for the black 
        method here
        */
        $this->prevMethod =__FUNCTION__;
        return $this;
        }
    
        public function white()
        { 
        /*
         your routine
        for the white
        method here
        */
        $this->prevMethod =__FUNCTION__;
        return $this;
        }
    
        public function colour() 
        {
        return $this->prevMethod;
        }
    
        }
    
    $c = new ColorChanger();
    $c->black->colour();
    $c->white()->colour();
    $c->black()->white->colourMethod();//will return white instead of black