PHP 的ArrayAccess接口 像數(shù)組一樣來訪問你的PHP對象
更新時間:2010年10月12日 22:58:23 作者:
如果想讓對象使用起來像一個 PHP 數(shù)組,那么我們需要實現(xiàn) ArrayAccess 接口
復(fù)制代碼 代碼如下:
interface ArrayAccess
boolean offsetExists($index)
mixed offsetGet($index)
void offsetSet($index, $newvalue)
void offsetUnset($index)
下面的例子展示了如何使用這個接口,例子并不是完整的,但是足夠看懂,:->
復(fù)制代碼 代碼如下:
<?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ù)庫相關(guān)的 getUserId() 方法。
相關(guān)文章
淺談ThinkPHP中initialize和construct的區(qū)別
下面小編就為大家?guī)硪黄獪\談ThinkPHP中initialize和construct的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04

