PHP 的ArrayAccess接口 像數(shù)組一樣來訪問你的PHP對象
更新時間:2010年10月12日 22:58:23 作者:
如果想讓對象使用起來像一個 PHP 數(shù)組,那么我們需要實現(xiàn) ArrayAccess 接口
復制代碼 代碼如下:
interface ArrayAccess
boolean offsetExists($index)
mixed offsetGet($index)
void offsetSet($index, $newvalue)
void offsetUnset($index)
下面的例子展示了如何使用這個接口,例子并不是完整的,但是足夠看懂,:->
復制代碼 代碼如下:
<?php
class UserToSocialSecurity implements ArrayAccess
{
private $db;//一個包含著數(shù)據(jù)庫訪問方法的對象
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'] 查找被執(zhí)行時,PHP 調(diào)用了 offsetGet() 方法,由這個方法再來調(diào)用數(shù)據(jù)庫相關的 getUserId() 方法。
相關文章
php中array_slice和array_splice函數(shù)解析
本文介紹了php中array_slice和array_splice函數(shù)解析,php拆分數(shù)組的二個函數(shù)(array_slice()、array_splice()),各舉一個例子,供大家學習參考。2016-10-10php實現(xiàn)按照權(quán)重隨機排序數(shù)據(jù)的方法
這篇文章主要介紹了php實現(xiàn)按照權(quán)重隨機排序數(shù)據(jù)的方法,是php數(shù)據(jù)排序中一個比較典型的應用技巧,需要的朋友可以參考下2015-01-01php jq jquery getJSON跨域提交數(shù)據(jù)完整版
getJSON跨域提交數(shù)據(jù),想必大家已在很多文章中見到過,下面的示例是php jq jquery getJSON跨域提交數(shù)據(jù)完整代碼,感興趣的朋友可以參考下2013-09-09PHP實現(xiàn)數(shù)組轉(zhuǎn)JSon和JSon轉(zhuǎn)數(shù)組的方法示例
這篇文章主要介紹了PHP實現(xiàn)數(shù)組轉(zhuǎn)JSon和JSon轉(zhuǎn)數(shù)組的方法,結(jié)合實例形式分析了php數(shù)組與json相互轉(zhuǎn)換實現(xiàn)方法與操作技巧,需要的朋友可以參考下2018-06-06