用PHP5和方法链输出一个属性


Output a property with PHP5 and method chaining

我正在玩PHP5和方法链,下面是几个StackOverflow示例。我想建立一个通用的show()方法,能够只打印所需的属性,请参见示例:

<?php
class testarea{
  public function set_a(){
    $this->property_a = 'this is a'.PHP_EOL;
    return $this;
  }
  public function set_b(){
    $this->property_b = 'this is b'.PHP_EOL;
    return $this;
  }
  public function show(){
   echo var_dump($this->property_a); // ->... generalize this                                                                                                                     
   return $this;
  }
}
$ta=new testarea();
$ta->set_a()->set_b();
$ta->show();
?>

string(10) "this is a "相呼应。

我想做的是一个通用的show()方法,它只显示set_a()set_b()方法所设置的属性。

有可能吗?

创建私有数组属性:

private $last = NULL;
private $setList = array();

在你的set_a()set_b()使用:

$this->last = 'line A';
$this->setList['a'] = $this->last;

$this->last = 'line B';
$this->setList['b'] = $this->last;

你的show()方法然后读:

foreach ($this->setList as $line) {
  var_dump($line);
}

或者如果您只需要最后一个属性集:

return $this->last;