手机
当前位置:查字典教程网 >编程开发 >php教程 >PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象
PHP 的ArrayAccess接口 像数组一样来访问你的PHP对象
摘要:复制代码代码如下:interfaceArrayAccessbooleanoffsetExists($index)mixedoffsetGet...

复制代码 代码如下:

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 的ArrayAccess接口 像数组一样来访问你的PHP对象】相关文章:

PHP中的traits简单使用实例

PHP递归调用数组值并用其执行指定函数的方法

在PHP的图形函数中显示汉字

PHP文件读取功能的应用实例

PHP遍历数组的方法汇总

PHP 判断数组是否为空的5大方法

PHP的伪随机数与真随机数详解

PHP图像处理类库及演示分享

PHP4 与 MySQL 数据库操作函数详解

类的另类用法--数据的封装

精品推荐
分类导航