Sobes.tech
Junior — Middle

Hangi özel yöntem, nesneye dizi veya öğe koleksiyonu gibi erişmeyi sağlar?

sobes.tech yapay zeka

AI'dan gelen yanıt

PHP'de özel ArrayAccess yöntemi, bir nesnenin dizi gibi davranmasını sağlar, yani öğelerine köşeli parantezler kullanarak erişilebilir.

Bunu yapmak için, sınıfın ArrayAccess arayüzünü uygulaması gerekir; bu arayüz dört yöntem içerir:

  • offsetExists($offset)$offset anahtarına sahip bir öğe olup olmadığını kontrol eder.
  • offsetGet($offset)$offset anahtarına sahip öğenin değerini döndürür.
  • offsetSet($offset, $value)$offset anahtarına $value değerini ayarlar.
  • offsetUnset($offset)$offset anahtarına sahip öğeyi siler.

Örnek:

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']; // 'value' yazdırır

Bu şekilde, ArrayAccess arayüzünün uygulanması, nesneye dizi gibi erişilmesine olanak tanır.