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

来源:互联网 发布:java多态的体现 编辑:程序博客网 时间:2024/05/17 07:12

方法一:

$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']);


方法二:构造一个类,实现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;
    }
}


阅读全文
0 0
原创粉丝点击