一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

PHP实现数组按数组方式访问和对象方式访问

时间:2015-03-12 编辑:简简单单 来源:一聚教程网


如何实现如下需求:


$data = array('x' => 'xx', 'y' => 'yy');
echo $data['x'];//输出xx
echo $data->x;//输出xx

方法一:构造一个类,实现ArrayAccess接口和__get,__set魔术方法


class Test implements ArrayAccess {
    private $data = null;
    public function __construct($data){
        $this->data = $data;
    }
    public function offsetGet($offset){
        return ($this->offsetExists($offset) ? $this->data[$offset] : null);
    }
    public function offsetSet($offset, $value){
        $this->data[$offset] = $value;
    }
    public function offsetExists($offset){
        return isset($this->data[$offset]);
    }
    public function offsetUnset($offset){
        if($this->offsetExists($offset)){
            unset($this->data[$offset]);
        }
    }
    public function __get($offset){
        return ($this->offsetExists($offset) ? $this->data[$offset] : null);
    }
    public function __set($offset, $value){
        $this->data[$offset] = $value;
    }
}

测试代码


$data = array('x' => 'x', 'y' => 'y');
$t = new Test($data);
printf("数组方式访问(\$t['x'])输出:%s
", $t['x']);
printf("对象方式访问(\$t->y)输出:%s
", $t->y);
//数组方式赋值,对象方式访问
$t['x1'] = 'x1';
printf("数组方式赋值%s
", "\$t['x1']='x1'");
printf("对象方式访问(\$t->x1)输出:%s
", $t->x1);
//对象方式赋值,数组方式访问
$t->y1 = 'y1';
printf("对象方式赋值%s
", "\$t->y1='y1'");
printf("数组方式访问(\$t['y1'])输出:%s
", $t['y1']);

PHP实现数组按数组方式访问和对象方式访问


方法二


$data = array('x' => 'x', 'y' => 'y');
$t = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
printf("数组方式访问(\$t['x'])输出:%s
", $t['x']);
printf("对象方式访问(\$t->y)输出:%s
", $t->y);
//数组方式赋值,对象方式访问
$t['x1'] = 'x1';
printf("数组方式赋值%s
", "\$t['x1']='x1'");
printf("对象方式访问(\$t->x1)输出:%s
", $t->x1);
//对象方式赋值,数组方式访问
$t->y1 = 'y1';
printf("对象方式赋值%s
", "\$t->y1='y1'");
printf("数组方式访问(\$t['y1'])输出:%s
", $t['y1']);
测试结果

PHP实现数组按数组方式访问和对象方式访问

热门栏目