Simple PHP Mehod Chaining
Method chaining is an advanced OOP concept in PHP. If you have experience in working with frameworks like CodeIgniter or CakePHP, you should have noticed a very convenient style of accessing different classes and methods and it looks something like this:
$obj->foo->bar->anotherMethod();
This technique in programming is known as method chaining. We’ll understand more about this fancy concept by the end of this blog post.
Method Chaining in Simple Class
class Music{ private $artiste; private $genre; public function setArtiste($artiste){ $this->artiste = $artiste; } public function setGenre($genre){ $this->genre = $genre; } public function displayArtiste(){ echo $this->artiste." belongs to the ".$this->genre. " genre."; } }
To access the class, we’ll create an object of the Music class:
$band = new Music(); $band->setArtiste('Aerosmith'); $band->setGenre('Hard Rock'); $band->displayArtiste();
This example will print:
Aerosmith belongs to the Hard Rock genre.
Introducing Method Chaining
To enable method chaining in our previous example, we need to add only a single line of code in each 'setXXX'
function. And that code is return $this;
.
Now our class looks like:
class Music { private $artiste; private $genre; public function setArtiste($artiste) { $this - > artiste = $artiste; return $this; //Returns object of 'this' i.e Music class } public function setGenre($genre) { $this - > genre = $genre; return $this; //Again, returns object of 'this' i.e Music class } public function displayArtiste() { echo $this - > artiste. " belongs to the ".$this - > genre. " genre."; } }
Now, we can finally access our class through fancy method chaining like this:
$band = new Music();
$band->setArtiste('Aerosmith')->setGenre('Hard Rock')->displayArtiste();
Explanation of Concept
Obvious, now you are slightly confused about what the f@#k is going on here. Let’s go through this code in baby steps. Before that, remember that method chaining in PHP always works from left to right.
$band = new Music()
creates a new object in the Music class.
Then, $band->setArtiste('Aerosmith')
assigns the name to a variable and returns the object of the same class. Now that $band->setArtiste('Aerosmith')
has become an object of the Music class, so we can access the Music class by using $band->setArtiste('Aerosmith')
as an object.
Next, we set the genre by using $band->setArtiste('Aerosmith')->setGenre('Hard Rock')
. setGenre()
again, returns the object of the class, so the complete phrase $band->setArtiste('Aerosmith')->setGenre('Hard Rock')
is again, now an object of Music.
Lastly, we’ll print out the band’s information by accessing the displayArtiste()
function:
$band->setArtiste('Aerosmith')->setGenre('Hard Rock')->displayArtiste();
And there you have it, basic method chaining.