用 PHP5 和方法链输出一个属性 [英] Output a property with PHP5 and method chaining

查看:53
本文介绍了用 PHP5 和方法链输出一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP5 和方法链,遵循几个 StackOverflow 示例.我想设置一个只能打印所需属性的通用 show() 方法,请参见示例:

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

?>

这与 string(10) "this is a " 相呼应.

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

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.

有可能吗?

推荐答案

创建私有数组属性:

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

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

In your set_a() and set_b() use:

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

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

您的 show() 方法然后读取:

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;

这篇关于用 PHP5 和方法链输出一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆