AssertionError class is a subclass of Error class. This type of error is thrown when assert() returns FALSE
assert() checks whether the given assertion is true or false, and if false, throws an AssertionError. The assert() function is defined as follows -
for PHP 5 and PHP 7 assert ( mixed $assertion [, string $description ] ) : bool PHP 7 only assert ( mixed $assertion [, Throwable $exception ] ) : bool
Serial number | Parameters and description |
---|---|
1 | assertion String or Boolean expression |
2 | description Failure message |
3 | exception (PHP 7 only) Throwable object |
Starting in PHP 7.0, assert() is now a language construct rather than a function. assertion The parameter can now be an expression, and the second parameter can be an exception or a description. Starting with PHP 7.2, string descriptions emit the E_DEPRECATED message. The AssertionError thrown by assert() will only be sent to the catch block if assert.exception=on is enabled in php.ini.
In this example, we assert that the condition is true and the try block executes normally. If the condition is false, an AssertionError message will be displayed from the catch block.
Live Demonstration
<?php $a=10; $b=20; try { if (assert($a == $b, "assert($a == $b) failed.")) { echo("assert($a == $b) was successful."); } } catch (AssertionError $e) { echo $e->getMessage(); } ?>
This will produce the following results -
assert(10 == 20) failed.
The above is the detailed content of PHP assertion error. For more information, please follow other related articles on the PHP Chinese website!