Method chaining is a technique in which methods are put together one after the other. For example you have a class employee and have three methods like this:

<?php
Class employee()
{    Public function id()
{
     // function code
}
   Public function name()
{      // function code
}    Public function salary()
{
     // function code
}
}
$obj= new employee(); // employee class object
$obj1->id(); 
$obj1->name(); $obj1->salary();
?>

 From the above example we can see if there are 3 functions then function is called via class each time or instead we can call using method chaining:

<?php
Class employee()
{
   Public function id()
{
     // function code
}
   Public function name()
{
     // function code
}
   Public function salary()
{
     // function code
}
}
$obj= new employee(); // employee class object
$obj1->id()->name()->salary();
Or you can also write in this way:
$obj1->id()
->name()
->salary();
?> 

In above example, both ways we can call more than one methods or functions. This process is called method chaining in PHP. This process works because always return object which is further called by another method. In this part we will discuss how to create method chaining and how to implement method chaining in PHP.

How to implement method chaining in PHP?

The main objective of method chaining in PHP is that it reduces the amount of code which is needed to call multiple function.

“PHP method chaining works because methods of the class return an object.”

Following is an example which shows how multiple chaining works:

In this example, there is a student class having three methods: fname(), lname() and addr()

<?php
class Myname {
    function __construct() {
        $this->thing = "g";
    }
    function abc() {
        $this->thing .= "x";
        return $this;
    }
    function xyz() {
        $this->thing .= "y";
        return $this;
    }
    function __tostring() {
        return $this->thing;
    }
}
$obj1 = new Myname();
echo $obj1->abc()->xyz()."</br>";
echo $obj1->abc()."</br>";
echo $obj1->xyz()."</br>";
echo $obj1;
?>

 

Output

gxy

gxyx

gxyxy

gxyxy



  Modified On Mar-15-2018 06:46:30 AM

Leave Comment