PHP's ArrayAccess interface ACTS as an array to access your PHP objects

  • 2020-03-31 21:09:46
  • OfStack

 
interface ArrayAccess 
boolean offsetExists($index) 
mixed offsetGet($index) 
void offsetSet($index, $newvalue) 
void offsetUnset($index) 

The following example shows how to use this interface, the example is not complete, but it is clear enough :->
 
<?php 
class UserToSocialSecurity implements ArrayAccess 
{ 
private $db;//An object containing a database access method
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']; 
?> 

In fact, when the $userMap['John'] lookup is executed, PHP calls the offsetGet() method, which in turn calls the database-related getUserId() method.

Related articles: