PHP 7 Assertions
PHP 7 assertions 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; it allows the first parameter to be an expression, not just a string to be evaluated or a boolean to be tested.
assert() Configuration
| Configuration Item | Default value | Optional values |
|---|---|---|
| zend.assertions | 1 |
|
1 - Generate and execute code (development mode)
0 - Generate code, but skip its execution
-1 - Do not generate code (production environment)
-
1 - Throw on assertion failure; an exception object can be thrown, and if no exception is provided, an AssertionError object instance is thrown.
-
0 - Use or generate Throwable, but only emit an object-based warning instead of throwing the object (compatible with PHP 5)
Parameters
- assertion
-
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 both the
assertionOn failure, the description option will be included in the failure message. - exception
-
In PHP 7, the second parameter can be an Throwable object, rather than a string; if the assertion fails and assert.exception is enabled, the object will be thrown.
Example
Set zend.assertions to 0:
Example
The output of the above program is:
Hi!
Set zend.assertions to 1 and assert.exception to 1:
Example
The output of the above program is:
Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
thrown in - on line 2
PHP 7 New Features