PHP 7 Exceptions

PHP 7 新特性PHP 7 New Features

PHP 7 exceptions are used for backward compatibility and to enhance the old assert() function. They enable zero-cost assertions in production environments and provide the ability to throw custom exceptions and errors.

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


assert() Configuration

Configuration optionsDefault valueOptional values
zend.assertions1
  • 1- Generate and execute code (development mode)

  • 0- Generate code, but skip it at execution time

  • -1- Do not generate code (production environment)

assert.exception0
  • 1- Throw when assertion fails. An exception object can be thrown; if no exception is provided, an instance of the AssertionError object is thrown.

  • 0- Use or generate Throwable, only generate object-based warnings instead of throwing the object (compatible with PHP 5)

Parameters

assertion

The assertion. In PHP 5, it is a string to be executed or a boolean to be tested. In PHP 7, it can be an expression that returns any value, and its execution result is used to indicate whether the assertion succeeded.

description

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

exception

In PHP 7, the second parameter can be anThrowableobject rather than a string. If the assertion fails and assert.exception is enabled, the object will be thrown.

Examples

Set zend.assertions to 0:

Examples

<?php
ini_set
('zend.assertions', 0);

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

The above program outputs:

Hi!

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

Examples

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

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

The above program outputs:

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

PHP 7 新特性PHP 7 New Features

Other extensions