本文實例講述了PHP對象鏈式操作實現原理。分享給大家供大家參考,具體如下:
什么是鏈式操作呢?使用jQuery的同學印象應該會很深刻.在jQuery中,我們經常會這樣的來操作DOM元素:
1
|
$( "p" ).css( "color" ).addClass( "selected" ); |
連貫操作看起來的確很酷,也非常的方便代碼的閱讀.那么在PHP里面是否可以實現呢?答案是肯定的,當然了必須是在OOP中用才行,在過程化的程序中,就沒有必要用這種方法了。
在PHP中,我們經常要使用很多函數:
1
2
|
$str = 'abs123 ' ; echo strlen (trim( $str )); |
上面代碼的作用就是去除字符串兩邊的空格,然后輸出其長度,那么使用鏈式編程就可以這樣來:
1
2
|
$str = 'abs123 ' ; echo $str ->trim()-> strlen (); |
是不是看著更加的舒服呢?這里主要是利用了PHP面向對象里面的 __call() 和 __toString() 魔術方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
/** * 對象鏈式操作 * 2015-04-24 */ class BaseChainObject{ /** * 追溯數據,用來進行調試 * @var array */ private $_trace_data = array (); /** * 保存可用方法列表 * @param array */ protected $_methods = array (); /** * 處理的數據 * @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(); |
從以上代碼可以看出,當調用對象中不存在的方法時,會自動觸發__call()魔術方法,然后結合call_user_func()來執行鏈式操作,當輸出對象的時候觸發toString()來輸出想要的結果.當然還有一個方案就是在自定義的方法中使用return this,也可以實現對象鏈式的操作,大家可以自己去試試看.
希望本文所述對大家PHP程序設計有所幫助。