PHP5 chaining methods example


// This Person class encapsulates a couple of properties which
// a person might have: their name and age.
// We also give the Person the opportunity to introduce themselves.
class Person
{
private $m_szName;
private $m_iAge;

public function setName($szName)
{
$this->m_szName = $szName;
return $this; // We now return $this (the Person)
}

public function setAge($iAge)
{
$this->m_iAge = $iAge;
return $this; // Again, return our Person
}

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

// We'll be creating me, digitally.
$peter = new Person();

// Let's set some attributes and let me introduce myself,
// all in one line of code.
$peter->setName('Peter')->setAge(23)->introduce();

// another one example

$peter->setAge(23)
->setName('Peter')
->setName('Winifred')
->setAge(72)
->introduce();

Read more: http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

http://stackoverflow.com/questions/7549423/how-do-i-chain-methods-in-php

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s