Itzhak Avraham Itzhak Avraham - 3 months ago 11
PHP Question

PHP - Call function from after call to another function in the class

I have this class:

class myClass
{
function A() {
$x = "Something ";
return $x;
}
function B() {
return "Strange";
}
}


But I want to call the function like this:

myClass()->A()->B();


How can i do that without return the class itself(return $this)?

Answer

In order to achieve method chaining, your methods from the chain (except the last one) must return an object (in many cases and also in yours $this).

If you would want to build a string with method chaining, you should use a property to store it. Quick example:

class myClass
{
    private $s = "";
    function A() {
        $this->s .= "Something ";
        return $this;
    }
    function B() {
        $this->s .= "Strange";
        return $this;
    }
    function getS() {
        return $this->s;
    }
}

// How to use it:
new myClass()->A()->B()->getS();