CKTIS / PHP
assert()
An enabled assert checks the truth of an expression and returns true on success.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
assert(mixed $assertion, Throwable|string|null $description = null): boolAn enabled assert checks the truth of an expression and returns true on success. On failure the default exception behavior raises AssertionError with the string description, or the supplied Throwable itself. With zend.assertions=0 or -1 the expression can be skipped and the call yields true. In PHP 8 a string assertion is tested for truth and never evaluated as source code.
Signature
assert(mixed $assertion, Throwable|string|null $description = null): bool
Example output
[1,"AssertionError","not enough"]
[0,true]
Examples
<?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);
Result
[1,"AssertionError","not enough"] [0,true]