经常疑惑在 PHP 中可以以数组和对象的属性两种方式获取某个变量值是如何实现的,原来只要数组实现了ArrayAccess接口便可以了。
class Person implements ArrayAccess
{
public function offsetExists($offset)
{
return isset($this->$offset);
}
public function offsetGet($offset)
{
return $this->$offset;
}
public function offsetSet($offset, $value)
{
$this->$offset = $value;
}
public function offsetUnset($offset)
{
unset($this->$offset);
}
}
$person = new Person();
$person->name = "hello";
echo $person['name']; //hello
var_dump((array)$person);//array(1) { 'name' => string(2) "cy"}
var_dump(isset($person));//bool(true)
unset($person['name']);
var_dump(isset($person));//bool(false)
暂时没有留言