Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

InvalidArgumentException

InvalidArgumentException è una LogicException che il codice può sollevare esplicitamente per un argomento di tipo inappropriato.

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

Sintassi

throw new InvalidArgumentException("string label required")

InvalidArgumentException è una LogicException che il codice può sollevare esplicitamente per un argomento di tipo inappropriato. Un parametro tipizzato può causare separatamente un TypeError del motore. La funzione label accetta mixed e rifiuta il numero in modo esplicito, mentre typed lo rifiuta con strict_types.

declare(strict_types=1);
function label(mixed $x): string {
    if (!is_string($x)) { throw new InvalidArgumentException("string label required"); }
    return strtoupper($x);
}
function typed(string $x): string { return $x; }
echo label("ok"), PHP_EOL;
foreach ([fn() => label(3), fn() => typed(3)] as $call) {
    try { $call(); } catch (Throwable $e) { echo get_class($e), PHP_EOL; }
}
OK
InvalidArgumentException
TypeError

Esempi

<?php
declare(strict_types=1);
function label(mixed $x): string {
    if (!is_string($x)) { throw new InvalidArgumentException("string label required"); }
    return strtoupper($x);
}
function typed(string $x): string { return $x; }
echo label("ok"), PHP_EOL;
foreach ([fn() => label(3), fn() => typed(3)] as $call) {
    try { $call(); } catch (Throwable $e) { echo get_class($e), PHP_EOL; }
}

Risultato

OK
InvalidArgumentException
TypeError

Fonti