Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / PHP

InvalidArgumentException

InvalidArgumentException je LogicException koju kod može izričito baciti za argument neodgovarajućeg tipa.

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

Sintaksa

throw new InvalidArgumentException("string label required")

InvalidArgumentException je LogicException koju kod može izričito baciti za argument neodgovarajućeg tipa. Deklarirani tip parametra može zasebno izazvati TypeError pogona. Funkcija label prima mixed i sama odbija broj, dok ga typed odbija uz 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

Primjeri

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

Rezultat

OK
InvalidArgumentException
TypeError

Izvori