【问题标题】:Output a property with PHP5 and method chaining使用 PHP5 和方法链接输出属性
【发布时间】:2013-05-15 00:40:00
【问题描述】:

我正在使用 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() 方法设置的属性。

有可能吗?

【问题讨论】:

    标签: php oop method-chaining


    【解决方案1】:

    创建私有数组属性:

    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;
    

    【讨论】:

    • 我是 OOP 和方法链的新手,所以这可能是一个不好的做法。但我的想法是,下面的方法可以从最后设置的属性中继承一些东西,或者如果指定了参数,则不继承。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多