PHP 7 exceptions

PHP 7 exceptions are used for backward compatibility and enhancement of the old assert() function. It enables zero-cost assertions in production environments and provides the ability to throw custom exceptions and errors.

The old version of the API will continue to be maintained for compatibility purposes. assert() is now a language construct that allows the first parameter to be an expression, not just a string to be evaluated or a The boolean to be tested.


assert() configuration

##assert.exceptionParameters
Configuration itemsDefault valueOptional value
zend.assertions1
  • ##1 - Generate and execute code (development mode)

  • 0 - Generate code but skip it during execution

  • -1 - No code generation (production environment)

0
  • 1

    - Thrown when an assertion fails, an exception object can be thrown, or an AssertionError object instance is thrown if no exception is provided.

  • 0

    - Use or generate Throwable, just generate warnings based on the object instead of throwing the object (compatible with PHP 5)

    assertion
  • Assertion. In PHP 5, a string for execution or a boolean for testing. In PHP 7, this can be an expression that returns any value, and the result will be used to indicate whether the assertion was successful.
  • description
  • If
  • assertion

    fails, the option description will be included in the failure message.

  • exception
  • In PHP 7, the second parameter can be a
  • Throwable

    object instead of a character A string that will be thrown if the assertion fails and assert.exception is enabled.

  • Example

Set zend.assertions to 0:

Example
<?php
ini_set('zend.assertions', 0);
assert(true == false);
echo 'Hi!';
?>

The above program is executed The output result is:

Hi!
Set zend.assertions to 1 and assert.exception to 1:

Example
<?php
ini_set('zend.assertions', 1);
ini_set('assert.exception', 1);
assert(true == false);
echo 'Hi!';
?>

The execution output of the above program is:

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


Next Section