CKTIS / PHP
InvalidArgumentException
InvalidArgumentException é uma LogicException que o código pode lançar explicitamente para um argumento de tipo inadequado.
Versão: PHP 8.4; repository runtime, production runtime not attested
Sintaxe
throw new InvalidArgumentException("string label required")InvalidArgumentException é uma LogicException que o código pode lançar explicitamente para um argumento de tipo inadequado. Um parâmetro tipado pode provocar separadamente um TypeError do motor. A função label recebe mixed e rejeita o número explicitamente, enquanto typed o rejeita com 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
Exemplos
<?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