查詢

ArrayAccess::offsetUnset()函式—用法及示例

「 復位一個偏移位置的值 」


ArrayAccess::offsetUnset() 是一個PHP內建介面 ArrayAccess 中的方法,用於從實現 ArrayAccess 介面的物件中移除指定偏移量的元素。

用法:

bool ArrayAccess::offsetUnset ( mixed $offset )

引數:

  • $offset:要移除的元素的偏移量。

返回值:

  • 如果成功移除了元素,則返回 true,否則返回 false

示例:

<?php
class MyArray implements ArrayAccess {
    private $data = [];

    public function offsetSet($offset, $value) {
        // 在指定偏移量的位置設定元素值
        $this->data[$offset] = $value;
    }

    public function offsetGet($offset) {
        // 獲取指定偏移量位置的元素值
        return $this->data[$offset];
    }

    public function offsetExists($offset) {
        // 檢查指定偏移量位置是否存在元素
        return isset($this->data[$offset]);
    }

    public function offsetUnset($offset) {
        // 從指定偏移量位置移除元素
        unset($this->data[$offset]);
    }
}

$array = new MyArray();
$array['foo'] = 'bar'; // 設定元素值
echo $array['foo'];   // 輸出: bar

unset($array['foo']); // 移除元素
echo $array['foo'];  // Notice: Undefined index: foo

?>

在上面的示例中,我們建立了一個自定義的類 MyArray,實現了 ArrayAccess 介面的相關方法。offsetUnset() 方法用於從 $data 陣列中移除指定偏移量位置的元素。

補充糾錯
上一個函式: ArrayAccess::offsetSet()函式
下一個函式: ArrayIterator::append()函式
熱門PHP函式
分享連結