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

yipeiwu_com5年前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利用header跳转失效的解决方法

本文实例讲述了PHP利用header跳转失效的解决方法,分享给大家供大家参考。具体方法分析如下: 一、问题: 今天header(\"Location: $url\"),以往跳转总是可以的...

PHPExcel实现表格导出功能示例【带有多个工作sheet】

本文实例讲述了PHPExcel实现表格导出功能。分享给大家供大家参考,具体如下: 首先得去下载phpexcel文档,解压下来 <?php /** * 简单实用Exec...

PHP中的string类型使用说明

注意:PHP没有对string的长度做限制。唯一限制的就是PHP在计算机中的可用内存(php.ini文件中的memory_limit变量的值) 限定字符串范围的方法有4中: 1、单引号;...

php 操作excel文件的方法小结

一、php,不用COM,生成excel文件 复制代码 代码如下: <? header("Content-type:application/vnd.ms-excel"); heade...

PHP中使用gettext来支持多语言的方法

我们今天用一个简单的实例说明一下在PHP中的getText的用法(getText是一系列的工具和库函数,帮助程序员和翻译人员开发多语言软件的), 从而实现PHP的i18n. 现在, 我们...