中央論壇 - CENTER BBS
標題:
[PHP] 物件多層指標:可連接多個 "->" 來連續處理、執行之物件寫法
[打印本頁]
作者:
郭子錢
時間:
2014-3-19 09:51
標題:
[PHP] 物件多層指標:可連接多個 "->" 來連續處理、執行之物件寫法
物件(Object) 在撰寫時, 會希望 於使用、操作上, 可以更直覺化(或更具擴充性), 下述的寫法就很常見.
$db->select('*')->limit(10)->begin(0) ... 等等. (在操作上(Method), 可以一直 "->" 的操作下去.)
執行順序:
select('*')
limit(10)
begin(0)
但是一般物件(Class)教學的寫法, 都只能 $db->select('*') 就結束了, 要再串接多個 ->, 就會直接出現錯誤訊息.
PHP Class - 標準物件的寫法
範例1
<?php
class Test
{
protected $str;
public function __construct()
{
}
public function a()
{
$this->str .= 'a';
}
public function b()
{
$this->str .= 'b';
}
public function display()
{
return $this->str . "\n";
}
}
/* 測試 */
$a = new Test();
$a->a(); // a
$a->b(); // b
// $a->a()->b(); // error
echo $a->display(); // ab
?>
複製代碼
PHP Class - 串接多個 "->" 的寫法
要串接多個 "->", 只要在 Function (Method) 的 回傳值(return value), 回傳 $this (物件本身) 即可. (將物件本身回傳, 即可繼續操作下去.)
範例2
<?php
class Test
{
protected $str;
public function __construct()
{
}
public function a()
{
$this->str .= 'a';
return $this;
}
public function b()
{
$this->str .= 'b';
return $this;
}
public function display()
{
return $this->str . "\n";
}
}
/* 測試 */
$a = new Test();
$a->a(); // a
$a->b(); // ab => a + b
$a->a()->b(); // abab => ab + a + b
echo $a->display(); // abab
?>
複製代碼
範例說明
範例1 的值就是每個執行完, 都是單獨的程序
範例2 的值, 會一直不斷的被累加起來(註: 字串一直接起來).
註: 其它程式語言也是相同作法.
出處:Tsung's Blog
歡迎光臨 中央論壇 - CENTER BBS (https://www.centerbbs.com/)
Powered by Discuz! X3