How to add PHP method chaining or create a fluent interface?

Spread the love

Sometimes, we want to add PHP method chaining or create a fluent interface.

In this article, we’ll look at how to add PHP method chaining or create a fluent interface.

How to add PHP method chaining or create a fluent interface?

To add PHP method chaining or create a fluent interface, we return $this in our object.

For instance, we write

<?php
class FakeString
{
    private $str;
    function __construct()
    {
        $this->str = "";
    }
    
    function addA()
    {
        $this->str .= "a";
        return $this;
    }
    
    function addB()
    {
        $this->str .= "b";
        return $this;
    }
    
    function getStr()
    {
        return $this->str;
    }
}

$a = new FakeString();

echo $a->addA()->addB()->getStr();

to create the FakeString class.

In it, we have the addA and addB return $this, which is the class instance, after concatenating a string to $this->str.

As a result, we can chain addA and addB like

$a->addA()->addB()->getStr()

since addA returns the class instance, which we use to call addB.

Conclusion

To add PHP method chaining or create a fluent interface, we return $this in our object.

Leave a Reply

Your email address will not be published. Required fields are marked *