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生成动态验证码gif图片

php生成动态验证码gif图片

这是一个通过php生成的动态验证码图片的示例,重点是可以运行哦!下面先发下效果图: 下面是php生成动态验证码需要用到的相关类和函数。 <?php /** *...

PHP中获取内网用户MAC地址(WINDOWS/linux)的实现代码

复制代码 代码如下: function ce_getmac() { if(PHP_OS == 'WINNT') { $return_array = array(); $temp_arra...

PHP中header和session_start前不能有输出原因分析

在http传输文本中,规定必须 header和content顺序必须是:header在前content在后,并且header的格式必须满足“keyword: value\n”这种格式。...

PHP 获取目录下的图片并随机显示的代码

当时想做一个随机更换背景图片的功能,用JavaScript写的话,程序流程应该是:建立一个图片数组->随机选择数组里其中一个值->生成样式并写入body标签。 可是用JS做的...

PHP实现根据时间戳获取周几的方法

本文实例讲述了PHP实现根据时间戳获取周几的方法。分享给大家供大家参考,具体如下: 获取某个时间戳的周几,以及未来几天以后的周几  其中: $time 代表时间  $...