Sobes.tech
Junior — Middle

Milline eriline meetod võimaldab objekti juurde pääseda nagu massiiv või elementide kogum?

sobes.tech AI

Vastus AI-lt

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

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

  • offsetExists($offset) — checks if an element with the key $offset exists.
  • offsetGet($offset) — returns the value of the element with the key $offset.
  • offsetSet($offset, $value) — sets the $value for the key $offset.
  • offsetUnset($offset) — removes the element with the 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']; // išveda 'value'

Thus, implementing the ArrayAccess interface allows you to access the object as if it were an array.