Sobes.tech
Junior — Middle

Which special method allows you to access an object as an array or collection of elements?

sobes.tech AI

Answer from AI

In PHP, the ArrayAccess interface allows an object to behave like an array, meaning you can access its elements using square brackets.

To do this, a class must implement the ArrayAccess interface, which contains four methods:

  • offsetExists($offset) — checks if an element with key $offset exists.
  • offsetGet($offset) — returns the value of the element with key $offset.
  • offsetSet($offset, $value) — sets the $value for the key $offset.
  • offsetUnset($offset) — removes the element with key $offset.

Example:

class MyCollection implements ArrayAccess {
    private $container = [];

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return $this->container[$offset] ?? null;
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }
}

$obj = new MyCollection();
$obj['key'] = 'value';
echo $obj['key']; // outputs 'value'

Thus, implementing ArrayAccess allows array-like access to objects.