Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / PHP

AssertionError

AssertionError es un Error que lanza una aserción falsa ejecutada con las excepciones de aserción activadas.

Versión: PHP 8.4; repository runtime, production runtime not attested

Sintaxis

assert($condition, "broken invariant")

AssertionError es un Error que lanza una aserción falsa ejecutada con las excepciones de aserción activadas. Una descripción de texto proporciona el mensaje y un Throwable suministrado se lanza en su lugar. Una aserción desactivada puede omitir la evaluación. El ejemplo inicia otro intérprete con aserciones activas.

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

Ejemplos

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

Resultado

AssertionError invariant
DomainException

Fuentes