Chaining in programming allows you to run muitple functions in a single statement like this: $obj->function()->function()
. How do you do this in PHP? All you do is return $this
in the function you wish to chain — as is demonstrated below.
class A {
public $value = 0;
public function increment() {
$this->value ++;
// Returning $this is what allows chaining to work
return $this;
}
}
$a = new A;
$a->increment()->increment();
echo $a->value; // $value is now 2
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from
Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.