PHP: Class methods catenation (chaining)

PHP: Class methods catenation (chaining)

Current OOP trick. Albeit this time not as functional, but as a visual. So - methods catenation or Class Methods chaining or ganging.

Method chaining is a technique that's common in high level programming languages. It is also used in the I/O handling of C++ standard library. Typically, method chaining simply consists of many methods on a class, each of which returns an object (possibly the current object itself).

$person = new Person();
$person->setAge(23)
->setName('Peter')
->setName('Winifred')
->setAge(72)
->introduce(); 

The result is: Hello my name is Winifred and I am 72 years old.

How?

The trick is at the the function returns. In this case, $ this.

class Person
{
  private $m_szName;
  private $m_iAge;

 public function setName($szName)
 {
  $this->m_szName = $szName;
  return $this;
 }

 public function setAge($iAge)
 {
  $this->m_iAge = $iAge;
  return $this;
 }

 public function introduce()
 {
  printf('Hello my name is %s and I am %d years old.',
  $this->m_szName,
  $this->m_iAge);
 }
} 

 

» Rate it!

(3)

» Related articles

» Comments

No comments
* mandatory
* not public
Besucherzahler ukraina brides
website counter
vimeo youtube     myspace facebook twitter
where to eat in riga?