0

我有这个代码:

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

4 回答 4

2

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

class one{
    public $instance;

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

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

此外,将属性与方法同名也是一个坏主意。这对解析器来说可能是明确的,但对开发人员来说却是令人困惑的。

于 2012-10-02T18:15:32.777 回答
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'
于 2012-10-02T18:20:01.787 回答
0

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

class one{
    public $instance;

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

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

然后你可以链接它们。

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

于 2012-10-02T18:15:57.393 回答
0

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

应该可以,但是您需要在方法中返回值。

于 2012-10-02T18:16:46.490 回答