method chaining in php5


phpপিএইচপি৫ এ মেথড চেইনিং
when we design class we should keep in mind that, how we could make it more user friendly in usage purpose and development purpose. now i’m talking about a feature introduced by php5 called method chaining as part of the oop improvement over php4. this enable us to do pretty cool things like:

$obj->methodX()->methodY()->.............->methodZ();

a small change between php4 and php5 is, in php5 method can return object. but this change help us to think in a new way to handle object and it’s methods.

normally  we use class in this way:

 <?php
 class Identity{
 private $name;
 private $occupation;
 private $age;

 function setName($name){
 $this->name = $name;
 }
 function setAge($age){
 $this->age = $age;
 }
 function setOccupation($occupation){
 $this->occupation = $occupation;
 }

 function showIdentity(){
 echo "Name: " . $this->name . "
";
 echo "Age : " . $this->age . "
";
 echo "Occupation: " . $this->occupation . "
";
 }
 }

 $id	=	new Identity();
 $id->setName("mahmud ahsan");
 $id->setAge(25);
 $id->setOccupation("software engineer");
 $id->showIdentity();
?>

so we used 5 lines of code to use Identity object for our purpose. but if we use method chaining then instead of 5 lines, we can write 2 lines of code for this purpose. and it becomes more readable and easy to understand.

now look at the below code:

<?php
 class Identity{
 private $name;
 private $occupation;
 private $age;

 function setName($name){
 $this->name = $name;
 return $this;
 }
 function setAge($age){
 $this->age = $age;
 return $this;
 }
 function setOccupation($occupation){
 $this->occupation = $occupation;
 return $this;
 }

 function showIdentity(){
 echo "Name: " . $this->name . "
";
 echo "Age : " . $this->age . "
";
 echo "Occupation: " . $this->occupation . "
";
 }
 }

 $id	=	new Identity();
 $id->setName("mahmud ahsan")->setAge(25)->setOccupation("software engineer")->showIdentity();
?>

at the above code look, we use return $this in some method, that’s why we could easily call $id->setName(‘…’)->setAge(…) ;

I found this method chaining is using rapidly in the components of zend framework.

mahmud ahsan

Computer programmer and hobbyist photographer from Bangladesh, lives in Malaysia. My [Business | Twitter | Linkedin | Instagram | Flickr | 500px]

You may also like

4 Comments

LEAVE A COMMENT