这个主要是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']));