Skip to content

PHP method chaining

Last updated on November 16, 2014

Method chaining means that you can chain method calls in one single statement.All the methods are mutator methods which will return the original object or other object. Mutator methods Returned Object will allow us to make calls in a chained manner.Method chaining is really simple isn’t it?.

If you have worked with CodeIgniter active records, Laravel or Zend Framework ..etc you must be familiar with method chaining. If not, don’t worry continue reading, at the end of this post ,you will get better understanding and you can create your own chainable methods.

For instance, consider the Test class which has 4 methods :

class Name {
    
    public $name;
    public $lastname;
    public $surname;
    
    public function setName($name) {
        $this->name = $name;
        return $this;
    }
    
    public function setLastName($lastname) {
        $this->lastname = $lastname;
        return $this;
    }
    
    public function setSurname($surname) {
        $this->surname = $surname;
        return $this;
    }
    
    public function getName() {
        return $this->name.' '.$this->lastname.' '. $this->surname;
    }
    
}

How to use

   $name = new Name;
   echo $name->setName('Arjun')->setLastName('PHP')->setSurname('Developer')->getName();
   // output: Arjun PHP Developer.

Note: Here getName() method must and should be called at the end , because it’s returning value(not object).

That’s it.We’re done.The major drawback to running chain methods is that you must return the object. You may not return any other value as you’re only allowed to return object.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments