assert

(PHP 4, PHP 5, PHP 7, PHP 8)

assertChecks an assertion

Description

assert(mixed $assertion, Throwable|string|null $description = null): bool

assert() is not a function but a language construct. allowing for the definition of expectations: assertions that take effect in development and testing environments, but are optimised away to have zero cost in production.

Assertions should be used as a debugging feature only. One use case for them is to act as sanity-checks for preconditions that should always be true and that if they aren't upheld this indicates some programming errors. Another use case is to ensure the presence of certain features like extension functions or certain system limits and features.

As assertions can be configured to be eliminated, they should not be used for normal runtime operations like input parameter checks. As a rule of thumb code should behave as expected even if assertion checking is deactivated.

assert() will check that the expectation given in assertion holds. If not, and thus the result is false, it will take the appropriate action depending on how assert() was configured.

The behaviour of assert() is dictated by the following INI settings:

Assert Configure Options
Name Default Description Changelog
zend.assertions 1
  • 1: generate and execute code (development mode)
  • 0: generate code but jump around it at runtime
  • -1: do not generate code (production mode)
 
assert.active true If false, assert() does not check the expectation and returns true, unconditionally.  
assert.callback null A user defined function to call when an assertion fails. It's signature should be:
assert_callback(
    string $file,
    int $line,
    null $assertion,
    string $description = ?
): void
Prior to PHP 8.0.0, the signature of the callback should be:
assert_callback(
    string $file,
    int $line,
    string $assertion,
    string $description = ?
): void
assert.exception true If true will throw an AssertionError if the expectation isn't upheld.  
assert.bail false If true will abort execution of the PHP script if the expectation isn't upheld.  
assert.warning true If true, will emit an E_WARNING if the expectation isn't upheld. This INI setting is ineffective if assert.exception is enabled.  
The options starting with assert. can be configured via assert_options(). However, this is not recommended.

Parameters

assertion

This is any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.

Warning

Prior to PHP 8.0.0, if assertion was a string it was interpreted as PHP code and executed via eval(). This string would be passed to the callback as the third argument. This behaviour was DEPRECATED in PHP 7.2.0, and REMOVED in PHP 8.0.0.

description

If description is an instance of Throwable, it will be thrown only if the assertion is executed and fails.

Note:

As of PHP 8.0.0, this is done prior to calling the potentially defined assertion callback.

Note:

As of PHP 8.0.0, the object will be thrown regardless of the configuration of assert.exception.

Note:

As of PHP 8.0.0, the assert.bail setting has no effect in this case.

If description is a string this message will be used if an exception or a warning is emitted. An optional description that will be included in the failure message if the assertion fails.

If description is omitted. A default description equal to the source code for the invocation of assert() is created at compile time.

Return Values

false if assertion is false, true otherwise.

Changelog

Version Description
8.0.0 assert() will no longer evaluate string arguments, instead they will be treated like any other argument. assert($a == $b) should be used instead of assert('$a == $b'). The assert.quiet_eval php.ini directive and the ASSERT_QUIET_EVAL constant have also been removed, as they would no longer have any effect.
8.0.0 If description is an instance of Throwable, the object is thrown if the assertion fails, regardless of the value of assert.exception.
8.0.0 If description is an instance of Throwable, no user callback is called even if it set.
8.0.0 Declaring a function called assert() inside a namespace is no longer allowed, and issues E_COMPILE_ERROR.
7.3.0 Declaring a function called assert() inside a namespace became deprecated. Such declaration now emits an E_DEPRECATED.
7.2.0 Usage of a string as the assertion became deprecated. It now emits an E_DEPRECATED notice when both assert.active and zend.assertions are set to 1.

Examples

Expectations

<?php
assert
(true == false);
echo
'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): assert(true == false) failed in - on line 2
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
  thrown in - on line 2

Example #1 Expectations with a custom exception

<?php
class CustomError extends AssertionError {}

assert(true == false, new CustomError('True is not false!'));
echo
'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): CustomError: True is not false! in -:4
Stack trace:
#0 {main} failed in - on line 4
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught CustomError: True is not false! in -:4
Stack trace:
#0 {main}
  thrown in - on line 4

Evaluated code assertions (PHP 7 only)

With evaluated code assertions, assert() callbacks can be particularly useful as the code used for the assertion is passed to the callback alongside information on where the assertion was done.

Example #2 Handle a failed assertion with a custom handler

<?php
// Activate assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
echo
"<hr>Assertion Failed:
File '
$file'<br />
Line '
$line'<br />
Code '
$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
$array = [];
assert('count($array);');
?>

Output of the above example in PHP 7.2:

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 21
<hr>Assertion Failed:
        File 'test.php'<br />
        Line '21'<br />
        Code 'count($array);'<br /><hr />

Output of the above example in PHP 7.1:

<hr>Assertion Failed:
        File 'test.php'<br />
        Line '21'<br />
        Code 'count($array);'<br /><hr />

Example #3 Using a custom handler to print a description

<?php
// Activate assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code, $desc = null)
{
echo
"Assertion failed at $file:$line: $code";
if (
$desc) {
echo
": $desc";
}
echo
"\n";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>

Output of the above example in PHP 7.2:

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 21
Assertion failed at test.php:21: 2 < 1

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 22
Assertion failed at test.php:22: 2 < 1: Two is less than one

Output of the above example in PHP 7.1:

Assertion failed at test.php:21: 2 < 1
Assertion failed at test.php:22: 2 < 1: Two is less than one

See Also