0%

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

经常疑惑在 PHP 中可以以数组和对象的属性两种方式获取某个变量值是如何实现的,原来只要数组实现了ArrayAccess接口便可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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)