CKTIS / PHP
OutOfBoundsException
OutOfBoundsException nasljeđuje RuntimeException i označava nevaljani indeks ili ključ.
Verzija: PHP 8.4; repository runtime, production runtime not attested
Sintaksa
throw new OutOfBoundsException("index missing")OutOfBoundsException nasljeđuje RuntimeException i označava nevaljani indeks ili ključ. Zbirka je može baciti pri provjeri granica, dok čitanje odsutnog ključa običnog polja u PHP-u 8.4 daje upozorenje i null. Funkcija array_key_exists razlikuje spremljeni null od odsutnog ključa.
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
Primjeri
<?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(); }
Rezultat
NULL OutOfBoundsException index 1