PHP 7 Exceptions
PHP 7 exceptions are used for backward compatibility and to enhance the old assert() function. They enable zero-cost assertions in production environments and provide the ability to throw custom exceptions and errors.
The old API will continue to be maintained for compatibility purposes. assert() is now a language construct that allows the first parameter to be an expression, rather than just a string to be evaluated or a boolean to be tested.
assert() Configuration
| Configuration options | Default value | Optional values |
|---|---|---|
| zend.assertions | 1 |
|
| assert.exception | 0 |
|
Parameters
- assertion
-
The assertion. In PHP 5, it is a string to be executed or a boolean to be tested. In PHP 7, it can be an expression that returns any value, and its execution result is used to indicate whether the assertion succeeded.
- description
-
If
assertionit fails, the description option will be included in the failure message. - exception
-
In PHP 7, the second parameter can be anThrowableobject rather than a string. If the assertion fails and assert.exception is enabled, the object will be thrown.
Examples
Set zend.assertions to 0:
Examples
ini_set('zend.assertions', 0);
assert(true == false);
echo 'Hi!';
?>
The above program outputs:
Hi!
Set zend.assertions to 1 and assert.exception to 1:
Examples
ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);
assert(true == false);
echo 'Hi!';
?>
The above program outputs:
Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
thrown in - on line 2
Other extensions
PHP 7 New Features