Home / Method chaining with PHP

Method chaining with PHP

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.