Method Chaining is a technique where different methods are chained together into single instruction. For example,

$dao->execute()->prepare($var) ;

The above method of chaining will work as long as the functions called will return an object to chain on. For example,

object->function_3();
(object-function_2())->function_3();      // function_3 still gets an obj
( ( object->function_1() )->function_2() )->function_3();   // finally

The class definition for this is:

<?php /** method chaining class */

class myclass{
public $var ;
public function_1(){
echo __FUNCTION__”\n” ;
return $this;
}

     public function_2(){
echo __FUNCTION__”\n” ;
return $this;
}

     public function_3(){
echo __FUNCTION__”\n” ;
return $this;
}

}

All the function above returns $this and can be chained.

Chaining can also be used on functions of different classes.

<?php
/** demostrate the chaining across different class */
class one{public function fx_one(){ echo Hello; }
}

class two{
public function fx_two(){
$one = new one();
return $one;
}

$two = new two():
$two->fx_two()->fx_one();

The logic here is also the same, fx_two() returns an object that contains fx_one() as a method inside it.

IMG-20160711-WA0007Arpan Dubey
IT Head, Infinity Technologies
dubey.arpan@gmail.com

Leave a Reply

Your email address will not be published. Required fields are marked *