文章網址:Bring some Ruby/Prototype flavour in your PHP array
原文轉錄如下:
You know that in ruby/prototype you can traverse thru each element of array like this Array.each(function(){/*function body*/}). It has also some methods like without(), inspect(), indexOf();last(), first() and others…. so how about implementing these cool methods in your regular PHP array?? No problem, lets extend the ArrayObject and have some fun. Here is the class.
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 64 65 66 67 68class ExtendedArrayObject extends ArrayObject { private $_array; public function __construct() { if (is_array(func_get_arg(0))) $this->_array = func_get_arg(0); else $this->_array = func_get_args(); parent::__construct($this->_array); } public function XArray() { parent::__construct($array); } public function each($callback) { $iterator = $this->getIterator(); while($iterator->valid()) { $callback($iterator->current()); $iterator->next(); } } public function without() { $args = func_get_args(); return array_values(array_diff($this->_array,$args)); } public function first() { return $this->_array[0]; } public function indexOf($value) { return array_search($value,$this->_array); } public function inspect() { echo "<pre>".print_r($this->_array, true)."</pre>"; } public function last() { return $this->_array[count($this->_array)-1]; } public function reverse($applyToSelf=false) { if (!$applyToSelf) return array_reverse($this->_array); else { $_array = array_reverse($this->_array); $this->_array = $_array; parent::__construct($this->_array); return $this->_array; } } public function shift() { $_element = array_shift($this->_array); parent::__construct($this->_array); return $_element; } public function pop() { $_element = array_pop($this->_array); parent::__construct($this->_array); return $_element; } }Now you can use it like this
1$newArray = new ExtendedArrayObject(array(1,2,3,4,5,6));or you can even construct it like this
1$newArray = new ExtendedArrayObject(1,2,3,4,5,6);then you can use these methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14function speak($value) { echo $value; } $newArray->each(<span style="color: red;">"speak"</span>)<span style="color: red;">;</span> $newArray->without(2,3,4); $newArray->i<span style="color: red;">n</span>spect(); $newArray->indexOf(5); $newArray->reverse(); $newArray->reverse(true); /*for changing array itself*/ $newArray->shift(); $newArray->pop(); $newArray->last(); $newArray->first();So how is this ExtendedArrayObject, like it?
Regards
Hasin Hayder
真的很厲害,這得把 PHP5 摸得相當熟稔才有辦法想到。
唉…看來我的 PHP5 高手之路還很長…
註:原來的程式有錯,紅色部份的部份是我加上去的。另外原作把 E_NOTICE 關掉,所以會把沒有用引號包住的 speak 當成字串傳遞,因此如果在 E_ALL 的狀況下會出現問題。