Output a property with PHP5 and method chaining

半城伤御伤魂 提交于 2019-12-11 14:06:11

问题


I am playing with PHP5 and method chaining, following several StackOverflow examples. I would like to set up a generic show() method able to print only the desired property, please see the example:

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

?>

This echoes string(10) "this is a ".

What I would like to do is a generic show() method which shows only the property that the set_a() or the set_b() methods have setted.

Is it possible?


回答1:


Create a private array property:

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

In your set_a() and set_b() use:

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

and

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

Your show() method then reads:

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

or if you only need the last property set:

return $this->last;


来源:https://stackoverflow.com/questions/16554973/output-a-property-with-php5-and-method-chaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!