1. 程式人生 > >PHP預定義介面之 ArrayAccess

PHP預定義介面之 ArrayAccess

ArrayAccess

  先說 ArrayAccess 吧!ArrayAccess 的作用是使得你的物件可以像陣列一樣可以被訪問。應該說 ArrayAccess 在PHP5中才開始有的,PHP5中加入了很多新的特性,當然也使類的過載也加強了,PHP5 中添加了一系列介面,這些介面和實現的 Class 統稱為 SPL。

ArrayAccess 這個介面定義了4個必須要實現的方法:

1 {
2    abstract public offsetExists ($offset)  //檢查偏移位置是否存在
3    abstract public offsetGet ($offset)     //
獲取一個偏移位置的值 4 abstract public void offsetSet ($offset ,$value) //設定一個偏移位置的值 5 abstract public void offsetUnset ($offset) //復位一個偏移位置的值 6 }

所以我們要使用ArrayAccess這個介面,就要實現相應的方法,這幾個方法不是隨便寫的,我們可以看一下 ArrayAccess 的原型:

複製程式碼
 1 /**
 2  * Interface to provide accessing objects as arrays.
 3  * @link http://php.net/manual/en/class.arrayaccess.php
4 */ 5 interface ArrayAccess { 6 7 /** 8 * (PHP 5 &gt;= 5.0.0)<br/> 9 * Whether a offset exists 10 * @link http://php.net/manual/en/arrayaccess.offsetexists.php 11 * @param mixed $offset <p> 12 * An offset to check for. 13 * </p> 14 * @return boolean true on success or false on failure.
15 * </p> 16 * <p> 17 * The return value will be casted to boolean if non-boolean was returned. 18 */ 19 public function offsetExists($offset); 20 21 /** 22 * (PHP 5 &gt;= 5.0.0)<br/> 23 * Offset to retrieve 24 * @link http://php.net/manual/en/arrayaccess.offsetget.php 25 * @param mixed $offset <p> 26 * The offset to retrieve. 27 * </p> 28 * @return mixed Can return all value types. 29 */ 30 public function offsetGet($offset); 31 32 /** 33 * (PHP 5 &gt;= 5.0.0)<br/> 34 * Offset to set 35 * @link http://php.net/manual/en/arrayaccess.offsetset.php 36 * @param mixed $offset <p> 37 * The offset to assign the value to. 38 * </p> 39 * @param mixed $value <p> 40 * The value to set. 41 * </p> 42 * @return void 43 */ 44 public function offsetSet($offset, $value); 45 46 /** 47 * (PHP 5 &gt;= 5.0.0)<br/> 48 * Offset to unset 49 * @link http://php.net/manual/en/arrayaccess.offsetunset.php 50 * @param mixed $offset <p> 51 * The offset to unset. 52 * </p> 53 * @return void 54 */ 55 public function offsetUnset($offset); 56 }
複製程式碼

 下面我們可以寫一個例子,非常簡單:

複製程式碼
 1 <?php
 2 class Test implements ArrayAccess
 3 {
 4     private $testData;
 5 
 6     public function offsetExists($key)
 7     {
 8         return isset($this->testData[$key]);
 9     }
10 
11     public function offsetSet($key, $value)
12     {
13         $this->testData[$key] = $value;
14     }
15 
16     public function offsetGet($key)
17     {
18         return $this->testData[$key];
19     }
20 
21     public function offsetUnset($key)
22     {
23         unset($this->testData[$key]);
24     }
25 }
26 
27   $obj = new Test();
28 
29   //自動呼叫offsetSet方法
30   $obj['data'] = 'data';
31 
32   //自動呼叫offsetExists
33   if(isset($obj['data'])){
34     echo 'has setting!';
35   }
36   //自動呼叫offsetGet
37   var_dump($obj['data']);
38 
39   //自動呼叫offsetUnset
40   unset($obj['data']);
41   var_dump($test['data']);
42 
43   //輸出:
44   //has setting!
45   //data  
46   //null
複製程式碼