Method Chaining in php

  • Avinash
  • 14
  • Sep 11, 2010
  • Web Development

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:

$obj->method1()->method2()->method3();
  $obj->method1()->method2()->method3();

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.

Regular Use of class

name=$name; } public function setAge($age="20") { $this->age=$age; } public function intro() { echo "Hello, My name is ".$this->name." and my age is ".$this->age." years."; } } ?>
<?php
 class person
 {
    private $name="";
    private $age="";

    public function setName($name="")
    {
      $this->name=$name;
    }
    public function setAge($age="20")
    {
      $this->age=$age;
    }
    public function intro()
    {
      echo "Hello, My name is ".$this->name." and my age is ".$this->age." years.";
    }
}
?>

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.

setName("xpertdeveloper"); $person->setAge("23"); $person->intro(); ?>
<?php
  $person = new person();
  $person->setName("xpertdeveloper");
  $person->setAge("23");
  $person->intro();
?>

Below is the output of the above code.

Hello, My name id xpertdeveloper and my age is 23 years.
Hello, My name id xpertdeveloper and my age is 23 years.

Implementing method chaining

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:

name=$name; return $this; } public function setAge($age="20") { $this->age=$age; return $this; } public function intro() { echo "Hello, My name is ".$this->name." and my age is ".$this->age." years."; } } ?>
<?php
class person
{
  private $name="";
  private $age="";

  public function setName($name="")
  {
    $this->name=$name;  
    return $this;
  }
  public function setAge($age="20")
  {
    $this->age=$age;
    return $this;
  }

  public function intro()
  {
    echo "Hello, My name is ".$this->name." and my age is ".$this->age." years.";
  }
}
 ?>

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:

setName("xpertdeveloper")->setAge("23")->intro(); ?>
<?php
  $person = new person();
  $person->setName("xpertdeveloper")->setAge("23")->intro();
?>

This will also give output same as our previous method.

How it works

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.

Related Posts

Written by Avinash

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:

  • Lipsey

    Excellent post, l quite agree with your conclusion. However lam having problem subscribing to your rss.

  • http://www.shower-cubicle.org Shower Cubicle

    ~.’ I am really thankful to this topic because it really gives up to date information ::*

  • http://brucealdridge.com bruce

    in the second snippet you need to add return $this

    • http://brucealdridge.com bruce

      * by second snippet, I mean second class snippet, ie the last code block

  • Bug

    You have forgot to add return $this in the amended class …

  • http://skebir.developpez.com Selim

    Hi, Great post.

    However. The code segment you give in the ‘Implementing method chaining’ paragraph and the one you give in the ‘Regular Use of class’ paragraph are exactly the same : There is no return $this statement at the end of each method.

  • KL

    you forgot to change your example code :)

  • http://artofwp.com Andreas Nurbo

    You have included the wrong code in the last code segment. Your set methods does not return any objects.
    Almost all cases of method chaining I’ve seen has been related to some sort of search.
    find(‘object’)->where(‘w=y’)->And(‘i>2’)-exec();

    PS
    The two earlier comments are just spam =).

  • t00ny

    Think you forgot the “return $this” in the amended class…

  • karl

    There is no return $this; in the second person class definition.

  • http://www.prsolucoes.com Paulo

    You need put “return $this” on each method of second class.

  • Stevan Goode

    Hiya,

    In your second class example, did you forget to return $this or am I missing something?

    Steve

  • http://www.xpertdeveloper.com Avinash

    Thanks to all for mentioning the mistake, updated :)