The main idea is to implement the ArrayAccess interface and __get, __set magic methods
<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>
Test:
<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>
The above has introduced PHP's implementation of accessing object properties in array mode, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.