PHP method chaining
Posted in Crosspost on July 31st, 2010 by Haris Nezirić – Be the first to commentMethod chaining is a really nice technique that adds class methods one on top the other. It’s commonly used in jQuery and some PHP framework modules.
The whole “magic” behind object chaining is made with a single line – “return $this” which is added in each method you wish chain.
So, in order to get this behavior in PHP:
[php]
$human = new Human;
$human->setName(‘Haris’)
->setAge(30)
->setSex(‘male’)
->display();
[/php]
you have to define class(es) like this:
[php]
class Human {
protected $_name;
protected $_age;
protected $_sex;
public function setName($name) {
$this->_name = $name;
return $this;
}
public function setAge($age) {
$this->_age = $age;
return $this;
}
public function setSex($sex) {
$this->_sex = $sex;
return $this;
}
public function display() {
printf(‘Hi, I\’m %s. I\’m %d years old, and I\’m %s!’,
$this->_name,
$this->_age,
$this->_sex
);
}
}
class Man extends Human {
protected $_sex = ‘male’;
}
class Woman extends Human {
protected $_sex = ‘female’;
}
[/php]
Now compare the methods called with method chaining and the old fashioned way
[php]
$woman = new Woman;
$woman->setName(‘Jane’)
->setAge(27)
->display();
$woman = new Woman;
$woman->setName(‘Jane’);
$woman->setAge(27);
$woman->display();
// Hi, I’m Jane. I’m 27 years old, and I’m female!
[/php]

