如何在一行中调用另一个方法之后的方法

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.

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

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