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变量可用字符

先来说说php变量的命名规则,百度下一抓一大把:(1) PHP的变量名区分大小写;(2) 变量名必须以美元符号$开始;(3) 变量名开头可以以下划线开始;(4) 变量名不能以数字字符开头...

php开启安全模式后禁用的函数集合

复制代码 代码如下: <?php ini_set("safe_mode",true); ?> 表 42-2. 安全模式限制函数 函数名 限制 dbmopen...

解决微信授权回调页面域名只能设置一个的问题

解决微信授权回调页面域名只能设置一个的问题

最终的解决方案是:https://github.com/liuyunzhuge/php_weixin_proxy,详细的介绍请往下阅读。 在做项目集成微信登录以及微信支付的时候,都需要进...

PHP随机字符串生成代码(包括大小写字母)

第一种:利用字符串函数操作 复制代码 代码如下: <?php function createRandomStr($length){ $str = '0123456789abcdef...

php5中date()得出的时间为什么不是当前时间的解决方法

相关设置是修改php.ini中的 date.timezone 参数: [Date] ; Defines the default ...