如何使用引用获取最后的方法输出?

时间:2014-08-12 16:54:48

标签: php oop method-chaining

我有这个难题,可以用引用来解决。我试图将这个&参考符号放在任何地方,尽管无济于事。

这是一个简化的脚本,用于演示我的基本应用程序。

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

现在,问题as you can see, the output will就是这样的。

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,可能只能获得最后一个数组。

由于

1 个答案:

答案 0 :(得分:1)

这个怎么样?

<?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++;
    }

如果你只想要一个最后一次打电话的数组我和@Adherence一起使用,如果没有分析你的代码会很复杂(很多!)这个东西......