PHP5 allows for method chaining, a feature common in other OOP languages. jQuery, for example, makes heavy use of method chaining.
Method chaining allows a developer to execute more functions on an object while using less code. Here’s some examples of what method chaining looks like:
$result = ClassName::getInstance()->loadItems()->render();
$result = $classInstance->action1()->action2('banana')->example();
$x = new ClassY();
$x->firstFunction()->secondFunction();
Method chaining is very easy to implement. All you need to do is set up your class with a bunch of functions which represent an atomic action to be performed, and each function needs to return the class (or even another class). This means that the result of the methods are executed, then the following link in the chain is executed against the result. Chains are executed from left to right.
Here’s an example class to show you how easy it’s done:
<?php
class ClassY {
function firstFunction() {
#execute code
return $this;
}
function secondFunction() {
#execute more code
return $this;
}
}
Now, make sure you don’t overdue it! Only use method chaining when it makes sense and the resulting code is prettier than what it would have been. Specifically, when you find yourself performing several class methods in a row.
The last link of the chain will usually perform some sort of action which will not return an instance of the class, and that is fine. A common example would be returning some rendered HTML which your class was building. If you NEED earlier chain links to return different data, you COULD use arguments passed by reference, but at that point your code will be uglier than it should be and a different approach would be ideal.