Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / PHP

InvalidArgumentException

InvalidArgumentException es una LogicException que el código puede lanzar explícitamente para un argumento de tipo inadecuado.

Versión: PHP 8.4; repository runtime, production runtime not attested

Sintaxis

throw new InvalidArgumentException("string label required")

InvalidArgumentException es una LogicException que el código puede lanzar explícitamente para un argumento de tipo inadecuado. Un parámetro tipado puede producir por separado un TypeError del motor. La función label recibe mixed y rechaza el número por sí misma, mientras typed lo rechaza 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

Ejemplos

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

Resultado

OK
InvalidArgumentException
TypeError

Fuentes