CKTIS / PHP
assert()
Включен assert проверява истинността на израза и при успех връща true.
Версия: PHP 8.4; repository runtime, production runtime not attested
Синтаксис
assert(mixed $assertion, Throwable|string|null $description = null): boolВключен assert проверява истинността на израза и при успех връща true. При неуспех стандартното поведение хвърля AssertionError с описание или подадения Throwable. При zend.assertions със стойност 0 или -1 изразът може да бъде пропуснат и резултатът е true. PHP 8 проверява низ като стойност без изпълнение на съдържанието.
Сигнатура
assert(mixed $assertion, Throwable|string|null $description = null): bool
Изход от примера
[1,"AssertionError","not enough"]
[0,true]
Примери
<?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);
Резултат
[1,"AssertionError","not enough"] [0,true]