CKTIS / PHP
OutOfBoundsException
OutOfBoundsException erft van RuntimeException en duidt een ongeldige index of sleutel aan.
Versie: PHP 8.4; repository runtime, production runtime not attested
Syntax
throw new OutOfBoundsException("index missing")OutOfBoundsException erft van RuntimeException en duidt een ongeldige index of sleutel aan. Een collectie kan haar na grenscontrole werpen, terwijl een ontbrekende gewone arraysleutel in PHP 8.4 een waarschuwing en null oplevert. De functie array_key_exists onderscheidt opgeslagen null van een ontbrekende sleutel.
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
Voorbeelden
<?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(); }
Resultaat
NULL OutOfBoundsException index 1