PHP實作物件屬性以數組方式存取

WBOY
發布: 2016-07-28 08:26:48
原創
1392 人瀏覽過

主要思路實作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>
登入後複製
').addClass(' pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介紹了 PHP實現物件屬性以數組方式訪問,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!