The method chain in PHP
In many frameworks, such as zend,cakephp, you will see the invocation of a class like
$obj->foo ()->bar ()->anothermethod ();
This is actually the use of the method chain in PHP call method, below to see an example to understand:
Class Person
{
Private $name;
Private $age;
Public Function SetName ($Name)
{
$this->name = $Name;
}
Public Function Setage ($AGE)
{
$this->age = $Age;
}
Public Function Findme ()
{
echo "My name is". $this->name. "and I AM". $this->age. "Years";
}
}
Normal method of invocation:
$myself = new Person ();
$myself->setname (' Arvind Bhardwaj ');
$myself->setage (' 22 ');
$myself->findme ();
Using the method chain:
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 the Person class
}
Public Function Findme ()
{
echo "My name is". $this->name. "and I AM". $this->age. "Years";
}
}
When called, you can:
$myself = new Person ();
$myself->setname (' Arvind Bhardwaj ')->setage (' n ')->findme ();
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.