/*
* ArrayAccess :Interface to provide accessing objects as arrays.
* 用访问数组的方式访问对象的
*/
class Foo implements ArrayAccess
{
private $container = [];
public function __construct()
{
$this->container = [
‘a‘=>1,
‘b‘=>2,
‘c‘=>3
];
}
public function offsetExists($offset)
{
// TODO: Implement offsetExists() method.
return isset($this->container[$offset]);
}
public function offsetGet($offset)
{
// TODO: Implement offsetGet() method.
return $this->container[$offset]??null;
}
public function offsetSet($offset, $value)
{
// TODO: Implement offsetSet() method.
$this->container[$offset] = $value;
}
public function offsetUnset($offset)
{
// TODO: Implement offsetUnset() method.
unset($this->container[$offset]);
}
}
$foo = new Foo();
$foo[‘d‘] = 321;
$foo[‘a‘] = 123;
var_dump(isset($foo[‘ae‘]));//bool(false)
var_dump(isset($foo[‘a‘]));//bool(true)
原文:https://www.cnblogs.com/jinshao/p/15018208.html