《PHP實(shí)戰(zhàn):PHP對象鏈?zhǔn)讲僮鲗?shí)現(xiàn)原理分析》要點(diǎn):
本文介紹了PHP實(shí)戰(zhàn):PHP對象鏈?zhǔn)讲僮鲗?shí)現(xiàn)原理分析,希望對您有用。如果有疑問,可以聯(lián)系我們。
本文實(shí)例講述了PHP對象鏈?zhǔn)讲僮鲗?shí)現(xiàn)原理.分享給大家供大家參考,具體如下:PHP編程
什么是鏈?zhǔn)讲僮髂?使用jQuery的同學(xué)印象應(yīng)該會很深刻.在jQuery中,我們經(jīng)常會這樣的來操作DOM元素:PHP編程
$("p").css("color").addClass("selected");
連貫操作看起來的確很酷,也非常的方便代碼的閱讀.那么在PHP里面是否可以實(shí)現(xiàn)呢?答案是肯定的,當(dāng)然了必須是在OOP中用才行,在過程化的程序中,就沒有必要用這種方法了.PHP編程
在PHP中,我們經(jīng)常要使用很多函數(shù):PHP編程
$str = 'abs123 '; echo strlen(trim($str));
上面代碼的作用就是去除字符串兩邊的空格,然后輸出其長度,那么使用鏈?zhǔn)骄幊叹涂梢赃@樣來:PHP編程
$str = 'abs123 '; echo $str->trim()->strlen();
是不是看著更加的舒服呢?這里主要是利用了PHP面向?qū)ο罄锩娴?__call() 和 __toString() 魔術(shù)方法PHP編程
/** * 對象鏈?zhǔn)讲僮? * 2015-04-24 */ class BaseChainObject{ /** * 追溯數(shù)據(jù),用來進(jìn)行調(diào)試 * @var array */ private $_trace_data = array(); /** * 保存可用方法列表 * @param array */ protected $_methods = array(); /** * 處理的數(shù)據(jù) * @param null */ public $data; function __construct($data){ $this->data = $data; $this->_trace_data['__construct'] = $data; return $this->data; } function __toString(){ return (String)$this->data; } function __call($name,$args){ try{ $this->vaild_func($name); }catch(Exception $e){ echo $e->getMessage(); exit(); } if (!$args) { $args = $this->data; $this->data = call_user_func($name,$args); }else{ $this->data = call_user_func_array($name,$args); } $this->_trace_data[$name] = $this->data; return $this; } /** * 判斷方法是否存在 * @param string */ private function vaild_func($fn){ if(!in_array($fn, $this->_methods)){ throw new Exception("unvaild method"); } } public function trace(){ var_dump($this->_trace_data); } } class String extends BaseChainObject{ protected $_methods = array('trim','strlen'); } $str = new String('ab rewqc '); echo $str->trim()->strlen(); $str->trace();
從以上代碼可以看出,當(dāng)調(diào)用對象中不存在的方法時,會自動觸發(fā)__call()魔術(shù)方法,然后結(jié)合call_user_func()來執(zhí)行鏈?zhǔn)讲僮?當(dāng)輸出對象的時候觸發(fā)toString()來輸出想要的結(jié)果.當(dāng)然還有一個方案就是在自定義的方法中使用return this,也可以實(shí)現(xiàn)對象鏈?zhǔn)降牟僮?大家可以自己去試試看.PHP編程
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》PHP編程
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助.PHP編程
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/3106.html