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

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

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

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

< ?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'].'';
echo $t['age'].'';
$t['from'] = '中国·安徽';
echo $t['from'].'';
echo $t->getName();
?>

将会输出:

Yozone
24
中国·安徽
Yozone

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


Share
  1. 2011年1月7日13:10

    But wanna remark that you have a very nice site, I like the style and design it actually stands out.