通过数组方式访问PHP对象属性

2010年5月21日 | 分类: PHP编程, 应用技巧 | 标签: , ,

以前看到过新版本的Symfony的Form文档,在类中可以通过$this['key']的方法来访问当前对象中的widgets,我一直很诧异,为什么可以这样用呢?我试验过很多方法都没成功,今天终于找到答案了。

方法其实很简单,需要在类中继承PHP预定义接口ArrayAccess,并且包含offsetGet, offsetSet, offsetExists和offsetUnset四个方法就可以实现上述功能了。下面来举个例子:

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
31
32
33
< ?php
class test implements ArrayAccess
{
  private $_result = array('name' => 'Yozone', 'age' => '24');
  public function offsetGet($key)
  {
    return $this->_result[$key];
  }
  public function offsetExists($key)
  {
    return isset($this->_result[$key]);
  }
  public function offsetSet($key, $value)
  {
    $this->_result[$key] = $value;
  }
  public function offsetUnset($key)
  {
    unset($key);
  }
  public function getName()
  {
    return $this['name'];
  }
}
 
$t = new test;
echo $t['name'].'<br />';
echo $t['age'].'<br />';
$t['from'] = '中国·安徽';
echo $t['from'].'<br />';
echo $t->getName();
?>

将会输出:

Yozone
24
中国·安徽
Yozone

没想到是如此的简单,今天收获很大,相当的Happy!
更多PHP预定义接口请到http://www.php.net/manual/en/reserved.interfaces.php查看

  • Share/Bookmark
目前还没有任何评论.