jocosn 2011-3-9 19:36
method chaining
method chaining([font=arial, sans-serif]方法鏈[/font]) 就是下面這種寫法
[color=#0000FF]$obj->foo()->bar()->anotherMethod();[/color]
PHP4 無法做到這個功能。PHP 5 要做到 method chaining([font=arial, sans-serif]方法鏈[/font]) ,就是在 method 最後加上 「return $this」
[color=#FF0000]傳統寫法[/color]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();
[color=#FF0000]method chaining([/color][font=arial, sans-serif][color=#FF0000]方法鏈[/color][/font][color=#FF0000]) [/color]
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();
wisdomleo 2011-6-19 11:35
回復 1# 的帖子
:hug: :hug: :hug: :hug: :hug: :handshake 提供資訊:) :)