如果想讓物件使用起來像一個 PHP 陣列,那麼我們需要實現 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() 方法。