Castle

我的沉思、笔记和回忆

PHP 中以数组方式访问对象的成员变量

技术

经常疑惑在 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)
创建于2017年09月25日 11:54
阅读量 626
留言列表

暂时没有留言

添加留言