PHP讓對象像數字一樣取值

PHP讓對象像數字一樣取值

來自專欄 鹹魚專場

ArrayAccess 讓對象像數組一樣賦值、讀取、刪除

interface ArrayAccess { function offsetExists($key); //被isset調用時 function offsetGet($key); //被當作數組讀時 function offsetSet($key, $value); //被當作數組賦值時 function offsetUnset($key); //被當作數組unset時 }

Iterator 讓對象像數組一樣循環

IteratorAggregate extends Traversable { abstract public Traversable getIterator ( void )}

example:完美的數組類

<?php /** * 測試介面的使用 * * @author zane * @since 2017-08-24 */ class arrayTest implements ArrayAccess, IteratorAggregate { protected $d = []; protected $currIndex = 0; protected $all = 0; protected $more = false; public function __construct($array) { $this->d = $array; $this->currIndex = 0; $this->all = count($this->d); $this->more = ($this->all > 0); } public function offsetExists($offset) { echo __METHOD__."
"; return array_key_exists($offset, $this->d); } public function offsetGet($offset) { echo __METHOD__."
"; return $this->d[$offset]; } public function offsetSet($offset, $value) { echo __METHOD__."
"; $this->d[$offset] = $value; } public function offsetUnset($offset) { echo __METHOD__."
"; unset($this->d[$offset]); return true; } public function getIterator() { return new ArrayIterator($this); }} $t = new arrayTest([a => A, b => B, c => C]); echo $t[a]; foreach($t as $key => $item){ echo "{$key} => {$item}
"; }

推薦閱讀:

數組基礎知識精華版
VBA數組和字典的經典用法及思路
4分鐘寫完C語言動態數組
數組,鏈表,二叉樹,這些是為了解決什麼問題而出現的呢?
Pandas Series用if判斷缺損值並修改,不影響原有空間

TAG:PHP | 數組 | 面向對象編程 |