Search code examples
phparraysdynamicmethodschaining

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();

Solution

  • 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.