主要思路實作ArrayAccess介面與__get,__set魔術方法
<code><span><span>class</span><span>ArrObject</span><span>implements</span><span>ArrayAccess</span> {</span><span>private</span><span>$_data</span>; <span>public</span><span><span>function</span><span>__construct</span><span>(<span>$data</span>)</span>{</span><span>$this</span>->_data = <span>$data</span>; } <span>public</span><span><span>function</span><span>offsetGet</span><span>(<span>$offset</span>)</span>{</span><span>return</span> (<span>$this</span>->offsetExists(<span>$offset</span>) ? <span>$this</span>->_data[<span>$offset</span>] : <span>null</span>); } <span>public</span><span><span>function</span><span>offsetSet</span><span>(<span>$offset</span>, <span>$value</span>)</span>{</span><span>$this</span>->_data[<span>$offset</span>] = <span>$value</span>; } <span>public</span><span><span>function</span><span>offsetExists</span><span>(<span>$offset</span>)</span>{</span><span>return</span><span>isset</span>(<span>$this</span>->_data[<span>$offset</span>]); } <span>public</span><span><span>function</span><span>offsetUnset</span><span>(<span>$offset</span>)</span>{</span><span>if</span>(<span>$this</span>->offsetExists(<span>$offset</span>)){ <span>unset</span>(<span>$this</span>->_data[<span>$offset</span>]); } } <span>public</span><span><span>function</span><span>__get</span><span>(<span>$offset</span>)</span>{</span><span>return</span> (<span>$this</span>->offsetExists(<span>$offset</span>) ? <span>$this</span>->_data[<span>$offset</span>] : <span>null</span>); } <span>public</span><span><span>function</span><span>__set</span><span>(<span>$offset</span>, <span>$value</span>)</span>{</span><span>$this</span>->_data[<span>$offset</span>] = <span>$value</span>; } }</code>
檢定:
<code><span>$data</span> = <span>array</span>(<span>'a'</span>=><span>'a'</span>,<span>'b'</span>=><span>'b'</span>,<span>'c'</span>=><span>'c'</span>); <span>$test</span> = <span>new</span> ArrObject(<span>$data</span>); <span>echo</span><span>$test</span>[<span>'a'</span>]; <span>//a</span><span>echo</span><span>$test</span>->a; <span>//a</span></code>
以上就介紹了 PHP實現物件屬性以數組方式訪問,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。