標題:
[技巧] method chaining
[打印本頁]
作者:
jocosn
時間:
2011-3-9 19:36
標題:
method chaining
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();
作者:
wisdomleo
時間:
2011-6-19 11:35
標題:
回復 1# 的帖子
提供資訊
歡迎光臨 ADJ網路實驗室 (http://dz.adj.idv.tw/)
Powered by Discuz! 6.0.0