i have been lately introduced to method chaining, and am not sure if what I\'m doing here is illegal, or I\'m doing it wrong. I have a database Class like:
c
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 Person
{
private $name;
private $age;
public function setName($Name)
{
$this->name = $Name;
return $this;//Returns object of 'this' i.e Person class
}
public function setAge($Age)
{
$this->age = $Age;
return $this;//Again returns object of 'this' i.e Person class
}
public function findMe()
{
echo "My name is ".$this->name." and I am ".$this->age. " years old.";
}
}
Now lets access our class methods through method chaining:
$myself = new Person();
$myself->setName('Arvind Bhardwaj')->setAge('22')->findMe();
Explanation of concept:
Surely you're a bit confused about precisely what is going on here. Lets go through this code in an easy way. Before that remember that method chaining always works from left to right!
$myself = new Person() creates a new object of the Person class, quite easy to guess though.
Next, $myself->setName('Arvind Bhardwaj') assigns the name to a variable and returns the object of the same class.
Now $myself->setName('Arvind Bhardwaj') has become an object of the Person class, so we can access the Person class by using $myself->setName('Arvind Bhardwaj') as an object.
Now we set the age as $myself->setName('Arvind Bhardwaj')->setAge('22'). setAge() again returns the object of this class, so the complete phrase $myself->setName('Arvind Bhardwaj')->setAge('22') is now an object of Person.
Finally we print the user information by accessing findMe method as:
$myself->setName('Arvind Bhardwaj')->setAge('22')->findMe();