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

2015-01-24信息快讯网

如果想让对象使用起来像一个 PHP 数组,那么我们需要实现 ArrayAccess 接口

 
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教程之PHP中shell脚本的使用方法分享
php tp验证表单与自动填充函数代码
PHP 设计模式之观察者模式介绍
php模拟post行为代码总结(POST方式不是绝对安全)
Trying to clone an uncloneable object of class Imagic的解决方法
Uncaught exception com_exception with message Failed to create COM object
php curl常见错误:SSL错误、bool(false)
在PHP中利用wsdl创建标准webservice的实现代码
PHP新手NOTICE错误常见解决方法
PHPExcel读取Excel文件的实现代码
DISCUZ在win2003环境下 Unable to access ./include/common.inc.php in... 的问题终极解决方案
提示Trying to clone an uncloneable object of class Imagic的解决
php学习笔记 面向对象中[接口]与[多态性]的应用
PHP面向接口编程 耦合设计模式 简单范例
PHP中用接口、抽象类、普通基类实现“面向接口编程”与“耦合方法”简述
解析PayPal支付接口的PHP开发方式
php park、unpark、ord 函数使用方法(二进制流接口应用实例)
发款php蜘蛛统计插件只要有mysql就可用
php中去除所有js,html,css代码
PHP入门学习笔记之一
PHP 显示客户端IP与服务器IP的代码
约瑟夫环问题的PHP实现 使用PHP数组内部指针操作函数
使用PHP 5.0创建图形的巧妙方法
POSIX 风格和兼容 Perl 风格两种正则表达式主要函数的类比(preg_match, preg_replace, ereg, ereg_replace)
PHP isset()与empty()的使用区别详解
php Notice: Undefined index 错误提示解决方法
PHP生成excel时单元格内换行问题的解决方法
php excel类 phpExcel使用方法介绍
php中使用ExcelFileParser处理excel获得数据(可作批量导入到数据库使用)
利用Memcached在php下实现session机制 替换PHP的原生session支持
Google Voice 短信发送接口PHP开源版(2010.5更新)
PHP 飞信好友免费短信API接口开源版
PHP+ACCESS 文章管理程序代码
php access 数据连接与读取保存编辑数据的实现代码
php 接口类与抽象类的实际作用
php面向对象全攻略 (十四) php5接口技术
火车头discuz6.1 完美采集的php接口文件
©2014-2024 dbsqp.com