PHP 8.0: Assertions throw exceptions by default

Version8.0
TypeChange

PHP supports Assertions with the assert() language construct since PHP 4. Until PHP 8.0, a failed assertion raised a warning by default, but not an exception.

assert(true === false);
// Warning: assert(): assert(true === false) failed in ... on line ...

To make the engine throw an exception, an INI option is needed:

[PHP]
assert.exception=1

In PHP 8.0, the default value for assert.exception INI value is changed from 0 to 1. This means failed assertions will throw an AssertionError exception by default.

assert(true === false);
// Fatal error: Uncaught AssertionError: assert(true === false) in ...:...

assert.warning INI value remains 1, but assert.exception=1 means an exception will be throw instead of a warning.

Assertion callback

There are no changes in the Assertion failure callback functionality.
Assertion callback will continue to receive the same information.

;INI configuration:
[Assertion]
assert.callback=assert_fail
// assert_options() can be used instead of an INI configuration.
// assert_options(ASSERT_CALLBACK, 'assert_fail');
assert(true === false);

function assert_fail(string $file, int $line , string $assertion, string $description = ''): void {
    // Do something with the failed assertions.
}

Assertion failure callback will not receive the AssertionError exception. Standard exception handling can be used to catch AssertionError exceptions. This is the same behavior as previous versions.

It is also possible to use ASSERT_CALLBACK/assert.callback callback without any further warnings or exceptions with an INI setting:

assert.exception=0
assert.warning=0
assert.callback=assert_fail

Backwards Compatibility Impact

Assertions are not meant to be used in production code. Throwing an exception by default in PHP 8.0 means assertion failures will be front and center.

Restoring the original functionality, although not recommended, is possible with an INI setting.:

[Assertion]
assert.exception=0
assert.warning=1

Related Changes


Implementation Discussion RFC (abandoned, 2019)