当前位置:首页 > PHP教程 > PHP高级教程

PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象

复制代码 代码如下:

interface arrayaccess
boolean offsetexists($index)
mixed offsetget($index)
void offsetset($index, $newvalue)
void offsetunset($index)

下面的例子展示了如何使用这个接口,例子并不是完整的,但是足够看懂,:->
复制代码 代码如下:

<?php
class usertosocialsecurity implements arrayaccess
{
private $db;//一个包含着数据库访问方法的对象
function offsetexists($name)
{
return $this->db->userexists($name);
}
function offsetget($name)
{
return $this->db->getuserid($name);
}
function offsetset($name, $id)
{
$this->db->setuserid($name, $id);
}
function offsetunset($name)
{
$this->db->removeuser($name);
}
}
$usermap = new usertosocialsecurity();
print "john's id number is " . $usermap['john'];
?>

实际上,当 $usermap['john'] 查找被执行时,php 调用了 offsetget() 方法,由这个方法再来调用数据库相关的 getuserid() 方法。
【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!