教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 PHP实现数组按数组方式访问和对象方式访问

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

发布时间:2016-10-08   编辑:jiaochengji.com
教程集为您提供PHP实现数组按数组方式访问和对象方式访问等资源,欢迎您收藏本站,我们将为您提供最新的PHP实现数组按数组方式访问和对象方式访问资源
下面来给各位介绍PHP实现数组按数组方式访问和对象方式访问例子,希望下文可以帮助到大家.


如何实现如下需求:


$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 <br />", $t['x']);
printf("对象方式访问(\$t->y)输出:%s <br />", $t->y);
//数组方式赋值,对象方式访问
$t['x1'] = 'x1';
printf("数组方式赋值%s <br />", "\$t['x1']='x1'");
printf("对象方式访问(\$t->x1)输出:%s <br />", $t->x1);
//对象方式赋值,数组方式访问
$t->y1 = 'y1';
printf("对象方式赋值%s <br />", "\$t->y1='y1'");
printf("数组方式访问(\$t['y1'])输出:%s <br />", $t['y1']);

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


方法二


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

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

您可能感兴趣的文章:
PHP实现数组按数组方式访问和对象方式访问
ASP内建对象Request
访问方式
聊聊php面向对象的编程基础(一)
什么是组合模式?(举例说明)
成员方法
php数组必知必会
smarty模板中get、post、request、cookies、session变量用法
PHP——MVC模式讲解与实例
PHP中的魔术方法总结

[关闭]
~ ~