PHP 7 - Expectations


Advertisements

Expectations are a backwards compatible enhancement to the older assert() function. Expectation allows for zero-cost assertions in production code, and provides the ability to throw custom exceptions when the assertion fails. assert() is now a language construct, where the first parameter is an expression as compared to being a string or Boolean to be tested.

Configuration directives for assert()

Directive Default value Possible values
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.exception 0

1 − throw, when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception was not provided.

0 − use or generate a Throwable as described above, but only generates a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

Parameters

  • assertion − The assertion. In PHP 5, this must be either a string to be evaluated or a Boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result is used to indicate whether the assertion succeeded or failed.

  • description − An optional description that will be included in the failure message, if the assertion fails.

  • exception − In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown, if the assertion fails and the assert.exception configuration directive is enabled.

Return Values

FALSE if the assertion is false, TRUE otherwise.

Example

<?php
   ini_set('assert.exception', 1);

   class CustomError extends AssertionError {}

   assert(false, new CustomError('Custom Error Message!'));
?>

It produces the following browser output −

Fatal error: Uncaught CustomError: Custom Error Message! in...
Advertisements