Synchronizing PHP method with dynamic names

I was wondering if it is possible to create a method chaining using the values ​​(or keys) of an array as dynamic method names.

For example, I have an array: $methods = ['first', 'second', 'third']

Can the next challenge be created?

first()->second()->third();

      

+3


source to share


2 answers


This has not been verified. Something like:

$object = null; // set this to an initial object to call the methods on

foreach ($methods as $value)
{
    $object = $object->$value();
}

      



Note that every method you call must return an object that has a method that will be called next. If it is an object of the same class, then it can simply return to itself using each chained method.

+3


source


You can also use the eval function. Example:



$object = new SomeClass(); // first, second, third
$methods = ['first', 'second', 'third'];

$callStr = 'return $object->';

foreach($methods as $method){
    $callStr.= $method . '()->';
}

$callStr = substr($callStr, 0, -2);
$callStr.= ';'; // return $object->first()->second()->third();

$result = eval($callStr); // return result of call - $object->first()->second()->third();

      

0


source







All Articles