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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-18 我要评论
想了解PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象的相关内容吗,在本文为您仔细讲解PHP ArrayAccess的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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() 方法。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们