php之像訪問陣列一樣訪問物件

胖爹啊發表於2020-11-12

這個主要是ArrayAccess(陣列式訪問)介面提供的能力,官網地址:https://www.php.net/manual/zh/class.arrayaccess.php

附上一個基礎版本示例:

<?php

/**
 * 陣列式訪問物件
 */
class Test implements arrayaccess
{
    public $vars;

    public function offsetExists($offset)
    {
        return isset($this->$offset);
    }

    public function offsetGet($offset)
    {
        return isset($this->$offset) ? $this->$offset : null;
    }

    public function offsetSet($offset , $value)
    {
        $this->$offset = $value;
    }

    public function offsetUnset($offset)
    {
        unset($this->$offset);
    }
}

$obj = new Test();

var_dump($obj['vars']);

$obj['vars'] = 2;

var_dump($obj['vars']);

var_dump(isset($obj['vars']));

unset($obj['vars']);

var_dump($obj['vars']);

var_dump(isset($obj['vars']));

相關文章