Easy Tutorial
❮ Func Cal Jdtojewish Func Filesystem Readlink ❯

PHP 7 Exceptions

PHP 7 New Features

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

Older versions of the API will continue to be maintained for compatibility purposes. assert() is now a language construct, which 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 Option Default Value Possible Values
zend.assertions 1 1 - Generate and execute code (development mode)<br>0 - Generate code but skip its execution<br>-1 - Do not generate code (production mode)
assert.exception 0 1 - Throw on failed assertions, can throw an exception object, or an AssertionError object instance if no exception is provided.<br>0 - Use or generate Throwable, just generate a warning based on the object rather than throwing it (compatible with PHP 5)

Parameters

The assertion. In PHP 5, it was a string to be executed or a boolean to be tested. In PHP 7, it can be an expression that returns any value, which will be used to determine if the assertion is successful.

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

In PHP 7, the second parameter can be a Throwable object instead of a string. If the assertion fails and assert.exception is enabled, this object will be thrown.

Examples

Setting zend.assertions to 0:

Example

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

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

The output of the above program is:

Hi!

Setting 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 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

PHP 7 New Features

❮ Func Cal Jdtojewish Func Filesystem Readlink ❯