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

相关文章

THINKPHP在添加数据的时候获取主键id的值方法

在使用ThinkPHP新增数据后可以很方便的获取自动增长型的主键值。 $Model = D(‘Blog'); $data['name'] = 'test'; $data['tit...

windows中PHP5.2.14以及apache2.2.16安装配置方法第1/2页

首先下载好需要安装的配置文件1、apache-2.2.162、php-5.2.14-Win32 一、apache配置 apache的安装不说了,安装过程中选择自己想安装的位置,一路nex...

PHP给前端返回一个JSON对象的实例讲解

解决问题:用php做后台时,如何给前端发起的AJAX请求返回一个JSON格式的"对象"; 说明:我本身是一个前端,工作久了之后发现要是不掌握一门后端开发语言的话,总感觉有点无力。最近在边...

php将字符串全部转换成大写或者小写的方法

本文实例讲述了php将字符串全部转换成大写或者小写的方法。分享给大家供大家参考。具体分析如下: php中可以通过strtolower和strtoupper两个函数将字符串中的每个英文字符...

如何在PHP程序中防止盗链

example:     页面: dl.php      --------------...