WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / PHP

AssertionError

AssertionError ist ein Error für eine ausgeführte falsche Zusicherung bei aktivierten Zusicherungsausnahmen.

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

Syntax

assert($condition, "broken invariant")

AssertionError ist ein Error für eine ausgeführte falsche Zusicherung bei aktivierten Zusicherungsausnahmen. Eine Zeichenkettenbeschreibung bestimmt die Meldung, ein übergebenes Throwable wird stattdessen geworfen. Eine deaktivierte Zusicherung kann die Auswertung ganz überspringen. Das Beispiel startet einen eigenen Interpreter mit aktivierten Zusicherungen.

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

Beispiele

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

Ergebnis

AssertionError invariant
DomainException

Quellen