Linas
Linas

Reputation: 4408

PHP OOP chaining methods

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

Upvotes: 0

Views: 137

Answers (4)

Mike Brant
Mike Brant

Reputation: 71384

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'

Upvotes: 1

Marcus
Marcus

Reputation: 8669

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

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

Upvotes: 0

Rudu
Rudu

Reputation: 15892

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

Upvotes: 0

cdhowie
cdhowie

Reputation: 169018

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.

Upvotes: 2

Related Questions