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实现的增强性mhash函数

今天使用php的加密函数mhash 的时候,报错: Fatal error : Call to undefined function mhash() mhash是php的内置函数但是使用...

php设计模式 Command(命令模式)

<?php /** * 命令模式 * * 将一个请求封装为一个对象从而使你可用不同的请求对客户进行参数化,对请求排除或记录请求日志,以及支持可取消的操作 */ interface...

zend framework多模块多布局配置

许多人在使用过程中都会遇到这样那样的问题,而且zend framework现在已经到1.11版本了,网络上的很多资料都还停留在旧版本上,因此我在这里以当前的最新版本1.11为例,来简单介...

PHP 简单日历实现代码

PHP 简单日历实现代码

复制代码 代码如下:<?php $monthoneday=date("Ym")."01"; $oneweekday=date("w",strtotime($monthoneday)...

用PHP去掉文件头的Unicode签名(BOM)方法

废话不多说,直接上代码 <?php //此文件用于快速测试UTF8编码的文件是不是加了BOM,并可自动移除 //By Bob Shen $basedir=".";...