Method chaining with PHP
Posted December 7th, 2008 in PHP (Updated January 5th, 2009)
Having used the Zend Framework on a couple of projects and spent a lot of time reading the documentation I discovered the use of method chaining. This post looks at how to use method chaining in PHP.
An example of method chaining from the Zend Framework documentation for the Zend_Mail component looks like this:
$mail = new Zend_Mail();
$mail->setBodyText('This is the text of the mail.')
->setFrom('somebody@example.com', 'Some Sender')
->addTo('somebody_else@example.com', 'Some Recipient')
->setSubject('TestSubject')
->send();
The above code could also be written like below, without method chaining:
$mail = new Zend_Mail();
$mail->setBodyText('This is the text of the mail.');
$mail->setFrom('somebody@example.com', 'Some Sender');
$mail->addTo('somebody_else@example.com', 'Some Recipient');
$mail->setSubject('TestSubject');
$mail->send();
Some people will like to use the method chaining way, and others the more traditional way as shown in the second example above.
If you want to be able to use method chaining yourself in your own code, your method simply needs to return the object itself, like so:
public function foo() {
... do something ...
return $this;
}
In the example above I have made the relevent line of code red to make it stand out. If you then had foo() bar() baz() and bat() methods you could then do this:
$myobject->foo()->bar()->baz()->bat();
You may not want or need to do this in any of your code, but the possibility is there if you wish to.
Update 05 Jan 2009: Thanks to "Ken" for the following information:
Method chaining utilizes a "fluent interface" ( http://en.wikipedia.org/wiki/Fluent_interface ) and can be used with any language that provides simple OO support. I first learned about this technique while studying jQuery (from Javascript), which heavily relies upon its fluent interface.
Related posts:
- Using the is_callable function in PHP (Thursday, January 22nd 2009)
- Using the Zend_Registry in PHP (Monday, January 19th 2009)
- Get the class name and parent class name in PHP (Wednesday, November 19th 2008)
- Sending email with Zend_Mail (Saturday, August 23rd 2008)
- Get a list of all available functions with PHP (Thursday, July 3rd 2008)
- Database error handling with the Zend Framework (Sunday, May 11th 2008)

Comments
blog comments powered by Disqus