База знанияИзпитен център
BGБългарски
Избери език13

CKTIS / PHP

OutOfBoundsException

OutOfBoundsException наследява RuntimeException и означава невалиден индекс или ключ.

Версия: PHP 8.4; repository runtime, production runtime not attested

Синтаксис

throw new OutOfBoundsException("index missing")

OutOfBoundsException наследява RuntimeException и означава невалиден индекс или ключ. Колекция може да го хвърли след проверка, докато четене на липсващ ключ от обикновен масив в PHP 8.4 дава предупреждение и null. Функцията array_key_exists отличава записано null от липса на ключ.

function fetchRow(array $rows, int $i): mixed {
    if (!array_key_exists($i, $rows)) { throw new OutOfBoundsException("index " . $i); }
    return $rows[$i];
}
var_dump(fetchRow([null], 0));
try { fetchRow([null], 1); }
catch (OutOfBoundsException $e) { echo get_class($e), " ", $e->getMessage(); }
NULL
OutOfBoundsException index 1

Примери

<?php
function fetchRow(array $rows, int $i): mixed {
    if (!array_key_exists($i, $rows)) { throw new OutOfBoundsException("index " . $i); }
    return $rows[$i];
}
var_dump(fetchRow([null], 0));
try { fetchRow([null], 1); }
catch (OutOfBoundsException $e) { echo get_class($e), " ", $e->getMessage(); }

Резултат

NULL
OutOfBoundsException index 1

Източници