주요 아이디어는 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 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.