WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / PHP

InvalidArgumentException

InvalidArgumentException ist eine LogicException, die Anwendungscode für einen ungeeigneten Argumenttyp ausdrücklich werfen kann.

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

Syntax

throw new InvalidArgumentException("string label required")

InvalidArgumentException ist eine LogicException, die Anwendungscode für einen ungeeigneten Argumenttyp ausdrücklich werfen kann. Ein deklarierter Parametertyp kann stattdessen einen Engine-TypeError auslösen. Die Funktion label akzeptiert mixed und weist die Zahl selbst zurück, typed scheitert unter 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

Beispiele

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

Ergebnis

OK
InvalidArgumentException
TypeError

Quellen