简体   繁体   中英

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

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.

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'

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM