method chaining(方法鏈) 就是下面這種寫法
$obj->foo()->bar()->anotherMethod();
PHP4 無法做到這個功能。PHP 5 要做到 method chaining(方法鏈) ,就是在 method 最後加上 「return $this」
傳統寫法class Person {
private $nickName;
private $fakeAge;
public function setName($strName){
$this->nickName = $strName;
}
public function setAge($intAge){
$this->fakeAge = $intAge;
}
public function Introduce(){
printf('Name: %s, Age: %d.', $this->nickName, $this->fakeAge);
}}
$f01 = new Person();
$f01->setName('King Willian');
$f01->setAge(16);
$f01->Introduce();
method chaining(方法鏈)
class Person{
private $nickName;
private $fakeAge;
public function setName($strName){
$this->nickName = $strName;
return $this;
}
public function setAge($intAge){
$this->fakeAge = $intAge;
return $this;
}
public function introduce(){
printf('Name: %s, Age: %d.', $this->nickName, $this->fakeAge);
}
}
$f01 = new Person();
$peter->setName('King Willian')->setAge(16)->introduce();
$peter->setName('King Willian')->setAge(16)->setName('Winner')->setAge(200)->introduce();