How can the ArrayAccess interface be utilized to enhance the functionality of wrapper classes in PHP?
The ArrayAccess interface in PHP allows objects to be accessed as arrays, providing a more intuitive way to interact with wrapper classes. By implementing the ArrayAccess interface in a wrapper class, you can use array syntax to access and manipulate the underlying data, making the class more versatile and easier to work with.
class Wrapper implements ArrayAccess {
private $data = [];
public function offsetExists($offset) {
return isset($this->data[$offset]);
}
public function offsetGet($offset) {
return $this->data[$offset];
}
public function offsetSet($offset, $value) {
$this->data[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->data[$offset]);
}
}
$wrapper = new Wrapper();
$wrapper['key'] = 'value';
echo $wrapper['key']; // Output: value