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

yipeiwu_com6年前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() 方法。

相关文章

PHP排序算法系列之直接选择排序详解

直接选择排序 直接选择排序(Straight Select Sorting) 的基本思想是:第一次从R[0]~R[n-1]中选取最小值,与R[0]交换,第二次从R[1]~R[n-1]中选...

PHP Parse Error: syntax error, unexpected $end 错误的解决办法

这几天写php程序,感觉很多地方不如asp,asp.Net,jsp顺手,比如session使用先得session_start();,文件跳转header用的也不方便.... 也许是不熟悉...

php,ajax实现分页

自己总结了些屁经验 1.用ajax post数据到后台页面后,接着要重新连接数据库,别以为用之前的session连接过就可以了 2.为了处理返回乱码的问题,我添加了header...

基于PHP实现假装商品限时抢购繁忙的效果

最近要做一个项目,有关商品显示抢购的功能。比如我们的网站很带流量,那么成千上万的用户在几秒内同时点你的商品,确实会出现“抢购人数过多,会提示,系统繁忙。   &nbs...

php 浮点数比较方法详解

浮点数运算精度问题 首先看一个例子: <?php $a = 0.1; $b = 0.9; $c = 1; var_dump(($a+$b)==$c); var_dump...