Synchronizing PHP method with dynamic names
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 to share
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 to share