0

I was looking to some php codes, and I saw an object that will call multiple methods in the same line.

I've tried to understand how to do it, and why we need to use it?

$object->foo("Text")->anotherFoo()->bar("Aloha")

What this styling called? and what is the best way to use it in php applications.

Othman
  • 2,942
  • 3
  • 22
  • 31

2 Answers2

5

This syntax is called method chaining, and it's possible because each method returns the object itself ($this). This is not necessarily always the case, it's also used to retrieve an object's property that in turn also can be an object (which can have properties that are objects, and so on).

It is used to reduce the amount of lines that you need to write code on. Compare these two snippets:

Without chaining

$object->foo("Text");
$object->anotherFoo();
$object->->bar("Aloha");

Using method chaining

$object->foo("Text")->anotherFoo()->bar("Aloha");
silkfire
  • 24,585
  • 15
  • 82
  • 105
  • if one method say returns 'false'. Will this still be valid? – Aris Sep 26 '13 at 12:42
  • @Aris Then you should get an error, which is actually correct, because it would be the same as writing `false->method();` – silkfire Sep 26 '13 at 12:43
  • so when is this valid? method must return $this? or is there an implicit rule in php that it returns the object itself? – Aris Sep 26 '13 at 12:45
  • @Aris The best thing would be to fail silently. For example, if it can't find a certain object, then do nothing. – silkfire Sep 26 '13 at 12:46
  • can I use it like this ? `$object = new Object()->setSomething()->andAlsoSetSomething();` – Othman Sep 26 '13 at 12:53
  • 1
    @Othman Yes, in PHP 5.4 you can create objects on the fly and use their methods directly: `$o = (new Object($arguments))->method(...)` – silkfire Sep 26 '13 at 13:17
0

this is used when the first function returns an object that will contains the second function that will return another object and so on...

class X
{

    public function A()
    {
        echo "A";
    }
    public function B()
    {
        echo "B";
    }

}
class Y
{

    public function A()
    {
        echo "Y";
    }
    public function B()
    {
        return $this;
    }

}

$y = new Y();
$y->B()->A();//this will run

$x = new X();
$x->A()->B();//this won't run, it will output "A" but then A->B(); is not valid
Soosh
  • 812
  • 1
  • 8
  • 24