duancong6937 2013-05-15 00:40
浏览 49
已采纳

使用PHP5和方法链接输出属性

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条回答 默认 最新

  • duanrui3480 2013-05-15 00:44
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)