如何使用引用获得最后一个方法的输出


How to get last methods output using references?

我有这个难题,可以通过参考文献来解决。我试图把这个&参考符号,只是无处不在,尽管无济于事。

下面是一个简化的脚本来演示我的基本应用程序。
<?php 
class main
{
    private $property = []; 
    function a()
    {
        $this->property[] = 'method: '.__METHOD__.' was called '; 
        return $this; 
    }
    function b()
    {
        $this->property[] = 'method: '.__METHOD__.' was called '; 
        return $this; 
    }
    function c()
    {
        $this->property[] = 'method: '.__METHOD__.' was called '; 
        return $this; 
    }
    function end()
    {
        var_dump($this->property);
    }
}

正如你所看到的,它是一个简单的类和它的方法,所有的方法都增加了一个类属性的值,所有的方法都返回类对象(是可链接的),除了end()方法。

现在,为了实现我的应用程序,我必须调用类方法

$a = new main;
$a->a()->end(); 
$a->b()->end(); 
$a->c()->end(); 

现在,您可以看到的问题是,输出将是这样的。

array(1) {
  [0]=>
  string(27) "method: main::a was called "
}
array(2) {
  [0]=>
  string(27) "method: main::a was called "
  [1]=>
  string(27) "method: main::b was called "
}
array(3) {
  [0]=>
  string(27) "method: main::a was called "
  [1]=>
  string(27) "method: main::b was called "
  [2]=>
  string(27) "method: main::c was called "
}

我要找的是,只得到最后一个数组。即:

array(3) {
  [0]=>
  string(27) "method: main::a was called "
  [1]=>
  string(27) "method: main::b was called "
  [2]=>
  string(27) "method: main::c was called "
}

因为,如我前面的代码所示,我是这样调用函数的。

$a = new main;
$a->a()->end(); 
$a->b()->end(); 
$a->c()->end(); 

获取最后一个数组而不是其他两个数组是有意义的。我意识到,达到这个目的的一种方法是,启动对象三次,如

(new main)->a()->end(); 
(new main)->b()->end(); 
(new main)->c()->end(); 

但是,我希望,在中间的某个地方,使用clonereference,可能只能得到最后一个数组。

谢谢

这个怎么样?

<?php 
class main
{
    private $property = []; 
    private $outputs  = 0;
    function a()
    {
        $this->property[$this->outputs][] = 'method: '.__METHOD__.' was called '; 
        return $this; 
    }
    function b()
    {
        $this->property[$this->outputs][] = 'method: '.__METHOD__.' was called '; 
        return $this; 
    }
    function c()
    {
        $this->property[$this->outputs][] = 'method: '.__METHOD__.' was called '; 
        return $this; 
    }
    function end()
    {
        var_dump($this->property);
        $this->outputs++;
    }
}

它不会给你最后一个数组,但是你可以从输出中得到它,如果你改变end方法:

    function end()
    {
        var_dump($this->property[$this->outputs]);
        $this->outputs++;
    }

如果你想只有一个数组的最后一次调用,我是@坚持,这是不可能的,没有分析你的代码复杂(很多!)这个东西…