user6184150
user6184150

Reputation:

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)?

Upvotes: 1

Views: 219

Answers (1)

Zoli Szabó
Zoli Szabó

Reputation: 4534

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

Upvotes: 4

Related Questions