php數組中物件如何存取

爱喝马黛茶的安东尼
發布: 2023-02-25 11:38:01
原創
3210 人瀏覽過

php數組中物件如何存取

如果在未做任何處理的情況下, 以數組的方式存取對象,會拋給你一個大大的錯誤。

Fatal error: Uncaught Error: Cannot use object of type Test as array
登入後複製

當然如果你對類別進行一些改造的話,還是可以像陣列一樣存取。

如何存取受保護的物件屬性

在正式改造之前,先看另一個問題。當我們試圖存取一個受保護的屬性的時候,也會拋出一個大大的錯誤。

Fatal error: Uncaught Error: Cannot access private property Test::$container
登入後複製

是不是受保護屬性就不能取得?當然不是,如果我們想要取得受保護的屬性,我們可以藉助魔術方法__get。

相關推薦:《php陣列

DEMO1

取得私有屬性

<?php
class Test 
{
    private $container = [];
    public function __construct()
    {
        $this->container = [&#39;one&#39;=>1, &#39;two&#39;=>2, &#39;three&#39;=>3];
    }
    
    public function __get($name)
    {
        return property_exists($this, $name) ? $this->$name : null;
    }
}
$test = new Test();
var_dump($test->container);
登入後複製

DEMO2

取得私有屬性下對應鍵名的鍵值。

<?php
class Test 
{
    private $container = [];
    
    public function __construct()
    {
        $this->container = [&#39;one&#39;=>1, &#39;two&#39;=>2, &#39;three&#39;=>3];
    }
    
    public function __get($name)
    {
        return array_key_exists($name, $this->container) ? $this->container[$name] : null;
    }
    
}
$test = new Test();
var_dump($test->one);
登入後複製

如何以陣列的方式存取物件

我們需要藉助預定義介面中的ArrayAccess介面來實作。介面中有4個抽象方法,需要我們實作。

<?php
class Test implements ArrayAccess
{
    private $container = [];
    public function __construct()
    {
        $this->container = [&#39;one&#39;=>1, &#39;two&#39;=>2, &#39;three&#39;=>3];
    }
    
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }
    
    public function offsetGet($offset){
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
    
    public function offsetSet($offset, $value)
    {
        if(is_null($offset)){
            $this->container[] = $value;
        }else{
            $this->container[$offset] = $value;
        }
    }
    
    public function offsetUnset($offset){
        unset($this->container[$offset]);
    }
    
}
$test = new Test();
var_dump($test[&#39;one&#39;]);
登入後複製

如何遍歷物件

其實物件在不做任何處理的情況下,也可以被遍歷,但是只能遍歷可見屬性,也就是定義為public的屬性。我們可以藉助另一個預先定義介面IteratorAggregate,來實作更為可控的物件遍歷。

<?php
class Test implements IteratorAggregate
{
    private $container = [];
    public function __construct()
    {
        $this->container = [&#39;one&#39;=>1, &#39;two&#39;=>2, &#39;three&#39;=>3];
    }
    
    public function getIterator() {
        return new ArrayIterator($this->container);
    }
    
}
$test = new Test();
foreach ($test as $k => $v) {
    var_dump($k, $v);
}
登入後複製

以上是php數組中物件如何存取的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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