Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / PHP

InvalidArgumentException

InvalidArgumentException jest wyjątkiem LogicException, który kod może jawnie zgłosić dla argumentu niewłaściwego typu.

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

Składnia

throw new InvalidArgumentException("string label required")

InvalidArgumentException jest wyjątkiem LogicException, który kod może jawnie zgłosić dla argumentu niewłaściwego typu. Deklarowany typ parametru powoduje osobny TypeError silnika. Funkcja label przyjmuje mixed i samodzielnie odrzuca liczbę, a typed odrzuca ją przez 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

Przykłady

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

Wynik

OK
InvalidArgumentException
TypeError

Źródła