Search

10/06/2009

石頭閒語:SPL:Use ArrayObject and ArrayIterator to Overload Operators of Array - 樂多日誌

SPL - Standard PHP Library
石頭閒語:SPL:Use ArrayObject and ArrayIterator to Overload Operators of Array - 樂多日誌
石頭閒語:為什麼還不升級PHP5 - 樂多日誌

舉例來說,ArrayAccess 中有4個方法, offsetGet, offsetSet, offsetExists, offsetUnset 。其中 offsetGet, offsetSet 按 C++ 觀點,其實就是 [] 運算子方法。 C++ 就直接寫成 operator[] 。 Ruby 寫成 [] 和 []= 。這一看就知道當我定義這方法後,便可像 primitive array 一樣用 [] 運算子存取內容。

我在 Google 上找到一個 ArrayAccess 的使用例子,結果作者全都寫成方法調用的形式 ($a->offsetGet(),...),而不是用 [] 運算子。似乎作者不知道可以這樣做, SPL 的優點完全沒有展現出來。

再說到 offsetExists, offsetUnset 。剛好在 magic methods 中也有一組 __isset, __unset 。問題就來了,為何 offsetExists, offsetUnset 不是 magic methods ;或者反過來說,為何要有 magic methods?

這不免令人感到混亂。

沒有留言: