php底層ArrayAccess類巧用分析

一、作用:提供像訪問數組一樣訪問對象的能力接口。

 二、 方法:

  1、offsetExists   檢查偏移位置是否存在

  2、offsetGet       獲取一個偏移位置的值。

  3、offsetSet       設置一個偏移位置的值。

  4、offsetUnset   刪除一個偏移位置的值。

三、代碼測試 

class ObjArray implements \ArrayAccess
{
    private $testData = [
        'title' => 'yinzheng'
    ];

    public function offsetExists($key)
    {
        return isset($this->testData[$key]);
    }

    public function offsetGet($key)
    {
        return $this->testData[$key];
    }

    public function offsetSet($key, $value)
    {
        $this->testData[$key] = $value;
    }

    public function offsetUnset($key)
    {
        unset($this->testData[$key]);
    }
}

四、結果 

        $obj = new \ObjArray();
        
        /**
         * 1、獲取
         * var_dump($obj['title']); //yinzheng
         */

        /**
         * 2、設置
         *  $obj['age'] = 32;
         * 3、獲取
         *  var_dump($obj['age']); // 32
         */
        
var_dump($obj);

/*
object(ObjArray)#34 (1) { ["testData":"ObjArray":private]=> array(1) { ["title"]=> string(8) "yinzheng" } }
*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章