SPL-ArrayAccess接口

ArrayAccess接口可以使用array的方式访问对象

<?php
class test implements ArrayAccess
{
    protected $propertyList;
    public function __construct($p = array())
    {
        $this->$propertyList = $p;
    }

    //检查偏移位置是否存在
    public function offsetExists($offset)
    {
        return isset($this->$propertyList[$offset]);
    }

    //获取一个偏移位置的值
    public function offsetGet($offset)
    {
        echo "get!\n";
        return $this->$propertyList[$offset];
    }

    //设置一个偏移位置的值
    public function offsetSet($offset, $value)
    {
        echo "set!\n";
        $this->$propertyList[$offset] = $value;
    }

    //复位一个偏移位置的值
    public function offsetUnset($offset)
    {
        unset($this->$propertyList[$offset]);
    }
}
$test1 = new test();
$test1['a'] = 'a';
print_r($test1->a);

通过以上两种方式都可以访问或修改对象。
Yii框架中的model类实现了该接口,可以通过array的形式访问数据记录。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。