最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
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']);
方法二
$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数组指针操作详解 04-05
- PHP实现判断数组是一维、二维或几维的方法 03-15
- PHP实现二维数组去重功能示例 01-13
- php如何从一个数组中随机的取出若干个不同的数的教程 01-03
- php中定义数组的方法详解 11-01
- php 判断数组是否为空的几种方法 03-27