PHP: Class Method Chaining
Another OOP trick. Though this time not about functionality, but about visual style. So - method chaining, also known as class methods chaining or ganging. For example: echo $thisDog->owner()->name();
Another OOP trick. Though this time not about functionality, but about visual style. So - method chaining, also known as class methods chaining or ganging.
Definition: The sequential linking of two or more data elements into a single whole. Data chaining is used in input/output channel control programs, as well as in lists located at different memory locations, indicating the next address.
LZA TK Information Technology, Telecommunications and Electronics Subcommittee term database
The notation in question:
$person = new Person();
$person->setAge(23)
->setName('Peter')
->setName('Winifred')
->setAge(72)
->introduce();
The result: Hello my name is Winifred and I am 72 years old.
How?
The trick lies in what 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);
}
}
Sources used:
http://www.phpandstuff.com/articles/php-method-chaining-plus-magic-setters
comments