1

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

1
  • What do you want to return? You should return object of class myClass to make chain calls. Commented Sep 3, 2016 at 18:07

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.