Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Method chaining with dynamic names

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();
like image 329
nteath Avatar asked Dec 07 '25 02:12

nteath


1 Answers

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.

like image 136
Marius Avatar answered Dec 08 '25 16:12

Marius