Reputation: 270
I was wondering if it's possible to create a method chaining using the values (or keys) of an array as the dynamic names of the methods.
For example, I have an array:
$methods = ['first', 'second', 'third']
Is it possible to create the following call ?
first()->second()->third();
Upvotes: 3
Views: 1943
Reputation: 243
You can also use 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();
Upvotes: -1
Reputation: 4016
This is untested. Something along the lines of:
$object = null; // set this to an initial object to call the methods on
foreach ($methods as $value)
{
$object = $object->$value();
}
Note that each method you call should return an object that has a method to be called next. If it's an object of the same class - then it can just return itself with each chainable method.
Upvotes: 3