Friday, October 30, 2009

jQuery-like chaining in PHP's Object Oriented Programming

It's interesting to see how object methods in PHP can be chained just like jQuery's chaining.

jQuery's chaining:


In PHP, it is also possible to chain similarly.

Using the string class from Samstyle PHP Framework, we can do chaining in PHP like this:

echo $str->trim()->replace('a', 'b')->value();

To do chaining in PHP, simply add a return statement at the end your methods where appropriate.

return $this;

Advisable to only do this kind of chaining for Action methods, meaning to say that these methods are only doing actions which are not supposed to return value.

Hope this helps!

No comments: