KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / PHP

assert()

Een actieve assert controleert de waarheidswaarde en geeft bij succes true terug.

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

Syntax

assert(mixed $assertion, Throwable|string|null $description = null): bool

Een actieve assert controleert de waarheidswaarde en geeft bij succes true terug. Bij mislukking werpt het standaardgedrag AssertionError met de beschrijving of de meegegeven Throwable. Bij zend.assertions op 0 of -1 kan evaluatie worden overgeslagen en is het resultaat true. PHP 8 test een tekenreeks als waarde zonder haar inhoud uit te voeren.

Signatuur

assert(mixed $assertion, Throwable|string|null $description = null): bool

Uitvoer van het voorbeeld

[1,"AssertionError","not enough"]
[0,true]

Voorbeelden

<?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;
}
$src = <<<'PHP'
$n = 0;
try {
    $ok = assert(++$n > 1, "not enough");
    echo json_encode([$n, $ok]);
} catch (AssertionError $e) {
    echo json_encode([$n, get_class($e), $e->getMessage()]);
}
PHP;
echo executeMode(1, $src), PHP_EOL, executeMode(-1, $src);

Resultaat

[1,"AssertionError","not enough"]
[0,true]

Bronnen