函式:ArrayAccess::offsetGet()
用法:ArrayAccess::offsetGet()函式用於獲取實現ArrayAccess介面的類物件中指定偏移量的值。
引數:offset (mixed) – 指定的偏移量。
返回值:成功時返回指定偏移量的值,失敗時丟擲異常。
示例:
<?php
class MyArray implements ArrayAccess {
private $container = ['foo' => 'bar', 'abc' => 'xyz'];
// 實現ArrayAccess介面的offsetGet()方法
public function offsetGet($offset) {
if ($this->offsetExists($offset)) {
return $this->container[$offset];
} else {
throw new Exception("Offset {$offset} does not exist!");
}
}
// 實現ArrayAccess介面的offsetExists()方法
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
// 實現ArrayAccess介面的offsetSet()方法
public function offsetSet($offset, $value) {
$this->container[$offset] = $value;
}
// 實現ArrayAccess介面的offsetUnset()方法
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
}
$array = new MyArray();
// 使用offsetGet()函式獲取指定偏移量的值
try {
$value1 = $array->offsetGet('foo');
echo "The value at offset 'foo' is: " . htmlspecialchars($value1) . "<br>";
} catch (Exception $e) {
echo "Exception: " . htmlspecialchars($e->getMessage()) . "<br>";
}
// 嘗試獲取不存在的偏移量的值
try {
$value2 = $array->offsetGet('123');
echo "The value at offset '123' is: " . htmlspecialchars($value2) . "<br>";
} catch (Exception $e) {
echo "Exception: " . htmlspecialchars($e->getMessage()) . "<br>";
}
?>
輸出:
The value at offset 'foo' is: bar
Exception: Offset 123 does not exist!
在上面的示例中,我們建立了一個名為MyArray
的類,該類實現了ArrayAccess
介面,並在其中定義了offsetGet()
方法。這個方法在透過$array->offsetGet('foo')
呼叫時,會返回'bar'
,因為偏移量'foo'
在類的內部容器中存在。然而,當嘗試透過$array->offsetGet('123')
獲取偏移量'123'
的值時,由於該偏移量不存在,所以會丟擲一個異常。