It seems method chaining has become more popular lately and a lot of people wonder how to do it, this simple tutorial will show you how.
The outcome would then become:
You can also reuse the methods in a single chain, such as:
Most people use this for eye-candy but it also makes code easier to read if coded properly.
Hope it helped,
Mark
PHP:
<?php
class Animal { //give the class a name
public function Dog() { //method
echo 'Woof';
return $this; //return Animal (this is basically what makes it chainable)
}
public function Cat() {
echo 'Meow';
return $this;
}
public function Sheep() {
echo 'Baa';
return $this;
}
}
$animal = new Animal();
$animal->Dog()->Cat()->Sheep();
?>
The outcome would then become:
WoofMeowBaa
You can also reuse the methods in a single chain, such as:
PHP:
$animal->Dog()->Cat()->Dog()->Dog()->Sheep();
Most people use this for eye-candy but it also makes code easier to read if coded properly.
Hope it helped,
Mark