源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-10-30 22:59 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象
[u]复制代码[/u] 代码如下:
interface ArrayAccess boolean offsetExists($index) mixed offsetGet($index) void offsetSet($index, $newvalue) void offsetUnset($index)
下面的例子展示了如何使用这个接口,例子并不是完整的,但是足够看懂,:->
[u]复制代码[/u] 代码如下:
<?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() 方法。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部