Php 简明教程

PHP – Expectations

预期是与旧的 assert() 函数向后兼容的增强功能。预期允许在生产代码中进行零成本的断言,并提供在断言失败时抛出自定义异常的能力。

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() 现在是一个语言构造,其中第一个参数与要测试的字符串或布尔值相反,是一个表达式。

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

下表列出了 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

  1. 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.

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

  3. 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,则返回 FALSE,否则返回 TRUE。

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!'));
?>

它将生成以下 output

It will produce the following output

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