PHP Tips and Tricks - Method Chaining

Guest Posts Paolo Nikko Nuñal

Another tip and trick that we are going to share with you is dealing with functions in PHP most especially when you are creating a class. Supposed you have a Person class.

Example:

<?php
 class Person{
    private $name;
    private $age;
    private $address;

   public function setName($name){
      $this->name = $name;
   }


   public function setAge($age){
      $this->age = $age;
   }


   public function setAddress($address){
      $this->address= $address;
   }
   public function getPerson(){
        echo $this->name." ".$this->age." ".$this->address;
   }
}


If you want to create a new Person, you have to call every member methods like the setName, setAge and setAddress to create a 'Person' with the following details. Your code may go like this.

 $person = new Person;
 $person->setName('John');
 $person->setAge(23);
 $person->setAddress('New York');


Although there is nothing wrong with the code,however you can do a neat new trick that you can easily create a new person aside from using a constructor. You can do this by return a $this statement on the functions and therefore you can call the other methods one after the other without having to create a new line. Modify your code with this.

   public function setName($name){
      $this->name = $name;
      return $this
   }


   public function setAge($age){
      $this->age = $age;
      return $this;
   }


   public function setAddress($address){
      $this->address= $address;
      return $this;
   }


After which you can call create a person by 'chaining' the methods.

$person->setName('John')->setAge(23)->setAddress('New York City');