assert

(PHP 4, PHP 5, PHP 7, PHP 8)

assert断言检测

说明

assert(mixed $assertion, Throwable|string|null $description = null): bool

assert() 不是函数,而是语言结构。允许定义预期(expectations):在开发和测试环境中生效的断言,但在生产环境中会优化掉以达到零成本。

断言应该只用于调试功能。其中一个用例是检查健全性的前提条件,应该始终为 true,如果不满足这些条件,则表示存在某些编程错误。 另一个用例是确保某些功能的存在,例如扩展函数或某些系统限制和特性。

由于断言可以配置为已消除,因此应该用于普通运行时操作,比如检查输入参数。一般来说,代码应该在禁用断言检查的情况下仍然按预期运行。

assert() 将检查 assertion 中指定的预期(expectations)是否成立。如果不成立,也就是结果为 false,它将根据 assert() 的配置采取适当的操作。

assert() 的行为由以下 INI 设置决定:

断言 配置选项
名字 默认 说明 更新日志
zend.assertions 1
  • 1:生成并执行代码(开发模式)
  • 0:生成代码但在运行时跳转
  • -1:生成代码但在运行时跳转(生产模式)
 
assert.active true false 时,assert() 将不会检查预期(expectation)并且无条件返回 true  
assert.callback null 当断言失败时,将调用用户定义的函数,其签名应该是:
assert_callback(
    string $file,
    int $line,
    null $assertion,
    string $description = ?
): void
在 PHP 8.0.0 之前,回调的签名应该是:
assert_callback(
    string $file,
    int $line,
    string $assertion,
    string $description = ?
): void
assert.exception true 如果为 true,则如果不能满足预期(expectations),将抛出 AssertionError 异常。  
assert.bail false true 时,如果预期(expectation)不支持,将会中止 PHP 脚本的执行。  
assert.warning true true 时,则如果预期(expectation)不支持,将发出 E_WARNING 警告。如果启用了 assert.exception,此 INI 设置将无效。  
assert. 开头的选项可以通过 assert_options() 进行配置。然而,这并不推荐使用。

参数

assertion

可以是任何带返回值的表达式,运行后的结果用于表示断言成功还是失败。

警告

在 PHP 8.0.0 之前,如果 assertionstring,将解释为 PHP 代码,并通过 eval() 执行。这个字符串将作为第三个参数传递给回调函数。这种行为在 PHP 7.2.0 中弃用,并在 PHP 8.0.0 中移除

description

如果 descriptionThrowable 的实例,只有在 assertion 执行失败时才会抛出。

注意:

自 PHP 8.0.0 开始,在调用可能定义的断言回调之前执行此操作。

注意:

自 PHP 8.0.0 开始,无论 assert.exception 的配置如何,都将会抛出该 object

注意:

自 PHP 8.0.0 开始,在这种情况下,assert.bail 设置不起作用。

如果 descriptionstring,当发出异常或警告时,将使用该消息。 如果 assertion 失败了,可选的 description 将会包括在失败信息里。

如果省略 description, 将在编译时创建默认 description,该 description 等于对 assert() 调用的源代码。

返回值

如果 assertion 是 false 则返回 false,否则为 true

更新日志

版本 说明
8.0.0 assert() 将不再对字符串参数求值,而是跟其他参数一样对待。应该使用 assert($a == $b) 替代 assert('$a == $b')。已移除 assert.quiet_eval php.ini 指令和 ASSERT_QUIET_EVAL 常量,因为它们不再有任何作用。
8.0.0 如果 descriptionThrowable 的实例,无论 assert.exception 的值如何,如果断言失败,该对象都会被抛出。
8.0.0 如果 descriptionThrowable 的实例,即使设置了用户回调,也不会调用该回调。
8.0.0 不再允许在命名空间中声明叫做 assert() 的函数,并发出 E_COMPILE_ERROR
7.3.0 弃用在命名空间中声明 assert() 函数。这样声明会发出 E_DEPRECATED
7.2.0 弃用使用 string 作为 assertion。当 assert.activezend.assertions 都设为 1 时,现在会发出 E_DEPRECATED 通知。

示例

Expectations

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

zend.assertions 设为 0,以上示例会输出:

Hi!

zend.assertions 设为 1,assert.exception 设为 0,以上示例会输出:

Warning: assert(): assert(true == false) failed in - on line 2
Hi!

zend.assertionsassert.exception 都设为 1,以上示例会输出:

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

示例 #1 包含自定义异常的 Expectations

<?php
class CustomError extends AssertionError {}

assert(true == false, new CustomError('True is not false!'));
echo
'Hi!';
?>

zend.assertions 设为 0,以上示例会输出:

Hi!

zend.assertions 设为 1,assert.exception 设为 0,以上示例会输出:

Warning: assert(): CustomError: True is not false! in -:4
Stack trace:
#0 {main} failed in - on line 4
Hi!

zend.assertionsassert.exception 都设为 1,以上示例会输出:

Fatal error: Uncaught CustomError: True is not false! in -:4
Stack trace:
#0 {main}
  thrown in - on line 4

Evaluated code assertions (PHP 7 only)

With evaluated code assertions, assert() callbacks can be particularly useful as the code used for the assertion is passed to the callback alongside information on where the assertion was done.

示例 #2 使用自定义处理程序处理失败的断言

<?php
// Activate assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
echo
"<hr>Assertion Failed:
File '
$file'<br />
Line '
$line'<br />
Code '
$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
$array = [];
assert('count($array);');
?>

Output of the above example in PHP 7.2:

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 21
<hr>Assertion Failed:
        File 'test.php'<br />
        Line '21'<br />
        Code 'count($array);'<br /><hr />

以上示例在 PHP 7.1 中的输出:

<hr>Assertion Failed:
        File 'test.php'<br />
        Line '21'<br />
        Code 'count($array);'<br /><hr />

示例 #3 使用自定义处理程序打印 description

<?php
// Activate assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code, $desc = null)
{
echo
"Assertion failed at $file:$line: $code";
if (
$desc) {
echo
": $desc";
}
echo
"\n";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>

Output of the above example in PHP 7.2:

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 21
Assertion failed at test.php:21: 2 < 1

Deprecated: assert(): Calling assert() with a string argument is deprecated in test.php on line 22
Assertion failed at test.php:22: 2 < 1: Two is less than one

以上示例在 PHP 7.1 中的输出:

Assertion failed at test.php:21: 2 < 1
Assertion failed at test.php:22: 2 < 1: Two is less than one

参见

add a note

User Contributed Notes 9 notes

up
26
hodgman at ali dot com dot au
15 years ago
As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."

This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool.
up
4
Tom
3 years ago
When migrating older code to PHP 7.2+, you may get E_DEPRECATED warnings for every call to assert() you ever wrote, urging you to not pass the assertion as a string.

It may be tempting to just run a regular expression across your files to convert all strings within "assert(...)" to statements. But, before you do that, be aware of the following caveat!

For example, this code simply asserts that $input is not empty.

assert('$input;');

This works, because the string passed to assert() is evaluated as a PHP statement and the result cast to Boolean.

If you want to have an equivalent statement that doesn't pass the first parameter as a string, your regular expression should rewrite this statement as:

assert((bool) ($input));

However, this looks a bit bulky and it is tempting to instead opt for the more direct approach to convert the above line to this:

assert($input);

But! This new statement will do one of three things:

1) Looks as if it worked as intended because $input just happens to be Boolean to begin with
2) Throw a parse error if $input is a string (best case)
3) Allow an attacker on a poorly configured server to execute arbitrary PHP-Code (worst case)

The reason is that, even though on PHP 7.2+ a E_DEPRECATED warning is raised, if assert() finds the first parameter to be a string, it will still execute it as PHP-Code, just as if it was called with a string to begin with.

If an attacker finds a way to manipulate the contents of $input, you might end up with a remote code execution vulnerability. So just be extra careful when migrating assertions.
up
6
mail<at>aaron-mueller.de
17 years ago
Here is a simple demonstration of Design By Contract with PHP

<?php

assert_options
(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 1);
assert_options(ASSERT_CALLBACK, 'dcb_callback');

function
dcb_callback($script, $line, $message) {
echo
"<h1>Condition failed!</h1><br />
Script: <strong>
$script</strong><br />
Line: <strong>
$line</strong><br />
Condition: <br /><pre>
$message</pre>";
}

// Parameters
$a = 5;
$b = 'Simple DCB with PHP';

// Pre-Condition
assert('
is_integer($a) &&
($a > 0) &&
($a < 20) &&

is_string($b) &&
(strlen($b) > 5);
'
);

// Function
function combine($a, $b) {
return
"Kombined: " . $b . $a;
}

$result = combine($a, $b);

// Post-Condition
assert('
is_string($result) &&
(strlen($result) > 0);
'
);

// All right, the Function works fine
var_dump($result);

?>
up
4
Krzysztof &#39;ChanibaL&#39; Bociurko
15 years ago
Note that func_get_args() should be used carefully and never in a string! For example:

<?php
function asserted_normal($a, $b) {
assert(var_dump(func_get_args()));
}
function
asserted_string($a, $b) {
assert('var_dump(func_get_args())');
}
?>

<?php asserted_normal(1,2) ?> prints
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}

but <?php asserted_string(3,4) ?> prints
array(1) {
[0]=>
string(25) "var_dump(func_get_args())"
}

This is because of that the string passed to assert() is being evaled inside assert, and not your function. Also, note that this works correctly, because of the eval scope:

<?php
function asserted_evaled_string($a, $b) {
assert(eval('var_dump(func_get_args())'));
}
asserted_evaled_string(5,6);
?>
array(2) {
[0]=>
int(5)
[1]=>
int(6)
}

(oh, and for simplicity's sake the evaled code doesn't return true, so don't worry that it fails assertion...)
up
1
Julien MOREAU aka PixEye
1 year ago
In order to change zend.assertions or assert.exception values, try with the ini_set() function but be aware that it may fail.

Example:
<?php
$ret
= @ini_set('zend.assertions', '1');
if (
$ret === false) echo 'ini_set() failed before line ', __LINE__, PHP_EOL;
up
-2
jason at jaypha dot com
5 years ago
You can take advantage of how assert is handled to use it for crude conditional compilation.

For example

<?php
assert
(print("Some debug message\n"));
assert(($val = "dev") || true);
?>

Since print() always returns 1, the topmost assertion will pass. For others, you may need to add a || true. Always enclose the expression in ().

In a development environment where zend.assertions=1, the above code will execute. In production environments where zend.assertions=-1, it wont even compile, thus not burdening performance.

Another, more real world, example.

<?php
$cssSrc
= 'https://code.jquery.com/jquery-3.2.1.min.js';
assert(($cssSrc = 'http://dev.local/jquery-3.2.1.js') || true);
echo
"<link rel='stylesheet' type='text/css' href='$cssSrc'/>\n";
?>

In a production environment, The website will use the minified version from the CDN. In a development environment, a development version, sourced locally, will be used instead.

Note: This will not work for everything. Only code that can be embedded in an expression will work.
up
-2
Ben
7 years ago
if there was no 'warning' message when assertion failed (FALSE), try reset the error handler:
<?php
set_error_handler
( null );
up
-5
uramihsayibok, gmail, com
13 years ago
There's a nice advantage to giving assert() some code to execute, as a string, rather than a simple true/false value: commenting.

<?php

assert
('is_int($int) /* $int parameter must be an int, not just numeric */');

// and my personal favorite
assert('false /* not yet implemented */');

?>

The comment will show up in the output (or in your assertion handler) and doesn't require someone debugging to go through your code trying to figure out why the assertion happened. That's no excuse to not comment your code, of course.

You need to use a block comment (/*...*/) because a line comment (//...) creates an "unexpected $end" parse error in the evaluated code. Bug? Could be.
(You can get around it with "false // not yet implemented\n" but that screws up the message)
up
-8
office dot stojmenovic at gmail dot com
10 years ago
Example from Ikac Framework how they use assert()

<?php

/**
* Set Assertion Debug
*
* This method will check the given assertion and take appropriate -
* action if its result is FALSE.
*
* This file is part of Ikac Framework.
*
* @package Ikac Framework
* @author Ivan Stojmenovic Ikac <contact.@stojmenovic.info>
*
* @param mixed $assertion The assertion.
* @param mixed $callback Callback to call on failed assertions
* @param array $options Set the various control options or just query their current settings.
* @param string $description An optional description that will be included in the failure message if the assertion fails.
*/
public function setAssertionDebug($assertion, $callback, array $options, $description = null)
{
if (
is_array($options)) {
foreach (
$options AS $option => $value) {
assert_options($option, $value);
}
}
if (
$callback) {
assert_options(ASSERT_CALLBACK, $callback);
}

return
assert($assertion, $description);
}
?>

How to use:

<?php
use Ikac\Component\SystemBehaviour\OptionsInfo;

$system = new OptionsInfo();

$option = array(ASSERT_ACTIVE => 1,ASSERT_WARNING => 0,ASSERT_QUIET_EVAL => 1);

$system->setAssertionDebug('2<1', function(){
echo
"Assertion failed";
},
$option);

?>
To Top