0

I have this code:

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
    }

    function execute(){
        $this->instance .= "and something happened";
    }
}

$class = new one;

$class->instance();
$class->execute();

echo $class->instance;

And it does what i expect it to do, but how can i chain actions, for example how could i call these functions in one line:

$class->instance()->execute();

And i know it's possible to do it like this:

one::instance()->execute();

but in this case i would need to have static functions which makes things complicated, i need some explanation on these things

4 Answers 4

2

In order for chaining to work, you need to return $this from each method you want to be chainable:

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
        return $this;
    }

    function execute(){
        $this->instance .= "and something happened";
        return $this;
    }
}

Also, it's a bad idea to give properties the same name as methods. It may be unambiguous to the parser, but it's confusing to developers.

Sign up to request clarification or add additional context in comments.

Comments

1

The general approach to chaining is to return $this as the return for any methods that needs to be chained. So, for your code, it might look like this.

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
        return $this;
    }

    function execute(){
        $this->instance .= "and something happened";
        return $this;
    }
}

So you cold do:

$one = new one;
$one->instance()->execute(); // would set one::instance to 'instance was createdand something happened'
$one->instance()->instance()->instance(); // would set one::instance to 'instance was created';
$one->instance()->execute()->execute(); / would set one::instance to 'instance was createdand something happenedand something happened'

Comments

0

You need to return the instance at the end of your functions:

class one{
    public $instance;

    function instance(){
        $this->instance = 'instance was created';
        return $this;
    }

    function execute(){
        $this->instance .= "and something happened";
        return $this;
    }
}

Then you can chain them.

By the way, this is probably just example code but your instance function doesn't actually create the instance ;)

Comments

0

$class->instance()->execute();

Should work but you need to return your values in your methods.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.