Pergunta

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?

Foi útil?

Solução

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;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top