查詢

SplObjectStorage::offsetExists()函式—用法及示例

「 檢查指定的物件是否存在於SplObjectStorage物件中 」


函式名稱:SplObjectStorage::offsetExists() 

適用版本:PHP 5 >= 5.3.0, PHP 7

函式描述:檢查指定的物件是否存在於SplObjectStorage物件中。

用法: bool SplObjectStorage::offsetExists ( object $object )

引數:

  • $object:要檢查的物件。

返回值: 如果物件存在於SplObjectStorage物件中,則返回true,否則返回false。

示例:

// 建立一個SplObjectStorage物件
$storage = new SplObjectStorage();

// 建立兩個物件
$obj1 = new stdClass();
$obj2 = new stdClass();

// 將物件與資料關聯並儲存到SplObjectStorage物件中
$storage->attach($obj1, "Data for obj1");
$storage->attach($obj2, "Data for obj2");

// 檢查物件是否存在於SplObjectStorage物件中
if ($storage->offsetExists($obj1)) {
    echo "obj1 exists in SplObjectStorage";
} else {
    echo "obj1 does not exist in SplObjectStorage";
}

if ($storage->offsetExists($obj2)) {
    echo "obj2 exists in SplObjectStorage";
} else {
    echo "obj2 does not exist in SplObjectStorage";
}

輸出:

obj1 exists in SplObjectStorage
obj2 exists in SplObjectStorage

在上面的示例中,我們建立了一個SplObjectStorage物件,並將兩個物件$obj1和$obj2與一些資料關聯起來。然後,我們使用SplObjectStorage::offsetExists()函式來檢查$obj1和$obj2是否存在於SplObjectStorage物件中。由於我們在建立物件時已經將它們新增到SplObjectStorage物件中,所以輸出結果表明兩個物件都存在於SplObjectStorage中。

補充糾錯
熱門PHP函式
分享連結