Overloading the Array Access Syntax
1. To overload array access syntax we have to implement ArrayAccess interface. That interface has four abstract function, so we should have implement all four functions.Those functions are
1. offsetExist - This function is used to check whether offset exists
2. offsetGet - This function is used to get the offset value
3. offsetSet - This function is used to set the offset value
4. offsetUnset - This function is used to unset the offset value
Example:
class Person implements ArrayAccess{
private $name;
private $id;
function offsetExists($name) {
;
}
function offsetGet($id) {
if($id == $this->id)
return $this->name;
else
return “not found”;
}
function offsetSet($name, $id) {
;
}
function offsetUnset($name) {
;
}
}
$objPerson = new Person();
$objPerson->offsetSet(”test”,”12″);
print “Person’s id is ” . $objPerson[”12″];
Above code is not a typical example for overloading array access syntax. Just implemented offsetGet() function whic will return person’s name.
In the above code
print “Person’s id is ” . $objPerson[”12″]; this will print the test.
