In this post I will explain the very useful feature which introduced in PHP5 as a part of OOP improvement over PHP4. This feature is called method chaining and you can do nice thing like below:
Well one change between PHP4 and PHP5 is that in PHP5 method can return objects. This small change have made the new way of handling objects and methods in PHP.
In order to implement the method chaining in PHP as explained earlier you must be able to return objects from methods. The returned object does not necessarily need be the same one from which the method is being called.
Now we can create a object of the class person and by calling the setName and setAge function we can set variable and finally by calling intro method we can introduce the person.
Below is the output of the above code.
To make the above class to behave for method chaining we have to make only changes to the above class. Actually methods in the above class is not returning anything, but to make chain works we will add return $this; to the end of the both function setName and setAge. So basically this functions will return the object of the class in which functions are placed. So now amended class will look like below:
Ok now in above class all methods have ability to return the object, so it enable us to group method call together in sequence or in chain as below code:
This will also give output same as our previous method.
If you are confused about what is going on here, then let me explain the code line by line.
First of all check this. $person->setName('xpertdeveloper'). This will call the setName method which will set the name of the person. after this method will return $this, that means it will return the object $person.
Next comes ->setAge(’23’). Because we are chained with previous method, PHP execute the setAge method of the returned object from the previous class, in our case it is $person. So with this method it will set the age and also return $this means object $person.
at last ->into(); which will print the introduction of the person as per criteria given in the previous methods.
Conclusion : We can make this article in one small sentence, If you return $this then you can chain the method calls together, Done :-)
Benefits : Code readability and reduction in code repetition.
Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.
View all posts by: Avinash