PHP OOP链接方法

时间:2012-10-02 18:12:28

标签: php method-chaining

我有这段代码:

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;

它完成了我期望它做的事情,但是我如何连锁动作,例如我怎么能在一行中调用这些功能:

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

我知道可以这样做:

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

但在这种情况下,我需要有静态函数,这会使事情变得复杂,我需要对这些事情做一些解释

4 个答案:

答案 0 :(得分:2)

为了使链接起作用,您需要从每个要链接的方法返回$this

class one{
    public $instance;

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

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

另外,给出与方法同名的属性是个坏主意。解析器可能是明确的,但它让开发人员感到困惑。

答案 1 :(得分:1)

链接的一般方法是将$this作为return返回给任何需要链接的方法。因此,对于您的代码,它可能看起来像这样。

class one{
    public $instance;

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

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

所以你冷酷的做法:

$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'

答案 2 :(得分:0)

您需要在函数结束时返回实例:

class one{
    public $instance;

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

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

然后你可以链接它们。

顺便说一句,这可能只是示例代码,但您的instance函数实际上并没有创建实例;)

答案 3 :(得分:0)

$类 - >实例() - >执行();

应该有效,但你需要在方法中返回你的值。