Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / PHP

AssertionError

AssertionError jest błędem Error zgłaszanym przez wykonaną fałszywą asercję przy włączonym zgłaszaniu wyjątków asercji.

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

Składnia

assert($condition, "broken invariant")

AssertionError jest błędem Error zgłaszanym przez wykonaną fałszywą asercję przy włączonym zgłaszaniu wyjątków asercji. Opis napisowy nadaje komunikat, a przekazany Throwable jest zgłaszany zamiast AssertionError. Wyłączona asercja może pominąć obliczenie wyrażenia. Przykład uruchamia osobny interpreter z włączonymi asercjami.

function executeMode(int $mode, string $source): string {
    $command = [PHP_BINARY, "-n", "-d", "zend.assertions=$mode", "-r", $source];
    $process = proc_open($command, [1 => ["pipe", "w"], 2 => ["pipe", "w"]], $pipes);
    if (!is_resource($process)) { throw new RuntimeException("start failed"); }
    $answer = stream_get_contents($pipes[1]);
    $error = stream_get_contents($pipes[2]);
    fclose($pipes[1]); fclose($pipes[2]);
    if (proc_close($process) !== 0) { throw new RuntimeException($error); }
    return $answer;
}
$code = <<<'PHP'
try { assert(false, "invariant"); }
catch (AssertionError $e) { echo get_class($e), " ", $e->getMessage(), PHP_EOL; }
try { assert(false, new DomainException("custom")); }
catch (DomainException $e) { echo get_class($e); }
PHP;
echo executeMode(1, $code);
AssertionError invariant
DomainException

Przykłady

<?php
function executeMode(int $mode, string $source): string {
    $command = [PHP_BINARY, "-n", "-d", "zend.assertions=$mode", "-r", $source];
    $process = proc_open($command, [1 => ["pipe", "w"], 2 => ["pipe", "w"]], $pipes);
    if (!is_resource($process)) { throw new RuntimeException("start failed"); }
    $answer = stream_get_contents($pipes[1]);
    $error = stream_get_contents($pipes[2]);
    fclose($pipes[1]); fclose($pipes[2]);
    if (proc_close($process) !== 0) { throw new RuntimeException($error); }
    return $answer;
}
$code = <<<'PHP'
try { assert(false, "invariant"); }
catch (AssertionError $e) { echo get_class($e), " ", $e->getMessage(), PHP_EOL; }
try { assert(false, new DomainException("custom")); }
catch (DomainException $e) { echo get_class($e); }
PHP;
echo executeMode(1, $code);

Wynik

AssertionError invariant
DomainException

Źródła