Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

OutOfBoundsException

OutOfBoundsException deriva da RuntimeException per un indice o una chiave non validi.

Versione: PHP 8.4; repository runtime, production runtime not attested

Sintassi

throw new OutOfBoundsException("index missing")

OutOfBoundsException deriva da RuntimeException per un indice o una chiave non validi. Una collezione può sollevarla dopo un controllo, mentre leggere una chiave assente da un array ordinario in PHP 8.4 emette un avviso e restituisce null. La funzione array_key_exists distingue il null memorizzato dalla chiave assente.

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

Esempi

<?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(); }

Risultato

NULL
OutOfBoundsException index 1

Fonti