Home > Article > Backend Development > PHP ArrayAccess interface example code introduction_PHP tutorial
interface ArrayAccess
boolean offsetExists($index)
mixed offsetGet($index)
void offsetSet($index, $newvalue)
void offsetUnset($index)
Example below Shows how to use this interface. The example is not complete, but it can be understood.
class UserToSocialSecurity implements ArrayAccess
{
private $db;//An object containing database access methods
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 "Johns ID number is " . $userMap[John];
?>
In fact, when $userMap[John] search is performed, PHP calls the offsetGet() method, and then from this method Call the database-related getUserId() method.