Search code examples
phpfluent-interface

How to chain internally within a class?


I wonder if we can chain 'internally' within a class itself? For instance, I have these two classes,

First class,

class Object1
{
    public $item;
    public $obj2;

    public function __construct() 
    {
        $this->obj2 = new Object2();
    }

    public function chain1()
    {
        $this->item = 'Chain1 ';

        return $this; 
    }

    public function chain2()
    {

        //$this->item = $this->obj2->chain3(); // works ok.
        $this->item = $this->obj2->chain3()->chain1(); // how to chain yourself?

        return $this;
    }
}

second class,

class Object2
{
    public $item;
    public function chain3()
    {
        $this->item = 'Chain 3 ';
        return $this; 
    }

    public function chain4()
    {
        $this->item = 'Chain4 ';
        return $this;
    }
}

$obj1 = new Object1();
print_r($obj1->chain2()->item);

error,

atal error: Call to undefined method Object2::chain1() in C:...

I need to chain chain1() in the class Ojbect1() itself.

$this->item = $this->obj2->chain3()->chain1(); 

Is it possible?


Solution

  • You can chain a method by returning $this from it:

    class foo
    {
        public $foo;
        public function yayThisChains()
        {
            return $this->chain()->chain2()->doIt();
        }
        private function doIt()
        {
            $this->foo = 'bar';
            return $this;
        }
        private function chain2() { return $this; }
        private function chain() { return $this; }
    }
    
    $foo = new foo();
    echo $foo->yayThisChains()->foo;
    

    The problem is you are trying to chain two different objects using the same $this. You could extend your classes so $this refers to the same class instead of building object2 in object1 through constructor:

    class Object2 extends Object1