加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

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

发布时间:2020-05-28 21:48:14 所属栏目:PHP 来源:互联网
导读:如果想让对象使用起来像一个 PHP 数组,那么我们需要实现 ArrayAccess 接口

<div class="codetitle"><a style="CURSOR: pointer" data="17647" class="copybut" id="copybut17647" onclick="doCopy('code17647')"> 代码如下:<div class="codebody" id="code17647">
interface ArrayAccess
boolean offsetExists($index)
mixed offsetGet($index)
void offsetSet($index,$newvalue)
void offsetUnset($index)

下面的例子展示了如何使用这个接口,例子并不是完整的,但是足够看懂,:->
<div class="codetitle"><a style="CURSOR: pointer" data="9361" class="copybut" id="copybut9361" onclick="doCopy('code9361')"> 代码如下:<div class="codebody" id="code9361">
<?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() 方法。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读