30% Therapy – 40% Practice – 30% Work project

PHP – Expectations



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()

The following table lists down the configuration directives for the assert() function −

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

Take a look at the following example −

<?php
   ini_set(''assert.exception'', 1);
   class CustomError extends AssertionError {}
   assert(false, new CustomError(''Custom Error Message!''));
?>

It will produce the following output

PHP Fatal error:  Uncaught CustomError: Custom Error Message! In test.php:6
Translate »