Search code examples
phpoopmethod-chainingstatic-functions

How to return function values when using method chaining in PHP?


Say I have the following class:

class Test
{

    private static $instance = false;

    public static function test()
    {
        if(!self::$instance)
        {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function test1()
    {
        //...
    }

    public function test2()
    {
        //...
    }

}

And I go about calling functions by chaining them like so:

$data = Test::test(...)->test1(...)->test2(...);

At the moment for the above method chain to work I have to keep returning $instance and I really would like it if I could return something from test2() to then be assigned to $data but I am not sure how to do this as I have to keep returning $instance in order for mt method chain to work?


Solution

  • If you want to chain methods, you need to return the current instance from any method which has another call chained on after it. However, it's not necessary for the last call in the chain to do so. In this case that means you're free to return whatever you like from test2()

    Just bear in mind, if you return something different from test2() you'll never be able to chain anything onto it in future. For example, $data = Test::test(...)->test2(...)->test1(...); wouldn't work.
    Protip: it's worth documenting your code with some comments explaining which ones are and aren't chainable so you don't forget in future.