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)—$offsetanahtarına sahip bir öğe olup olmadığını kontrol eder.offsetGet($offset)—$offsetanahtarına sahip öğenin değerini döndürür.offsetSet($offset, $value)—$offsetanahtarına$valuedeğerini ayarlar.offsetUnset($offset)—$offsetanahtarı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.