Assertion Failures Throw Exceptions by Default in PHP 8.0

Assertion Failures Throw Exceptions by Default in PHP 8.0

PHP supports assertions that trigger an error when a condition is not met. Mostly, assertions are used for testing or debugging purposes during development. PHP provides assert language construct that allows to perform assertions.

The assert construct behavior is controlled by assert.exception INI option. This option has two possible values.

No.ValueDescription
1.0If assertion fails then a warning will be emitted.
2.1If assertion fails then AssertionError will be thrown.

In versions prior to PHP 8.0, the default value for assert.exception option is 0. This means that a warning is emitted on an assertion failure by default.

In the following code the x value must be positive, otherwise an assertion fails:

<?php

$x = -1;
assert($x > 0);

In versions prior to PHP 8.0, we get a warning:

Warning: assert(): assert($x > 0) failed in main.php on line 4

Since 8.0, the default value for assert.exception option is 1. This means that an exception is thrown on an assertion failure by default.

Fatal error: Uncaught AssertionError: assert($x > 0) in main.php:4

Note that this behavior is by default. The value for assert.exception option can be changed in the php.ini file or using the ini_set function at runtime.

<?php

ini_set('assert.exception', 0);

$x = -1;
assert($x > 0);

Example will emit a warning and doesn't matter which PHP version is used:

Warning: assert(): assert($x > 0) failed in main.php on line 6

Leave a Comment

Cancel reply

Your email address will not be published.