assert

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

assert检查断言是否为 false

说明

PHP 5 和 7

assert(mixed $assertion, string $description = ?): bool

PHP 7

assert(mixed $assertion, Throwable $exception = ?): bool

assert() 会检查指定的 assertion 并在结果为 false 时采取适当的行动。

传统断言(PHP 5 和 7)

如果 assertion 是字符串,它将会被 assert() 当做 PHP 代码来执行。如果传入了 boolean 的条件作为 assertion,这个条件将不会作为参数传递给 assert_options() 定义的断言回调。相反,回调将会收到空字符串。

断言这个功能应该只被用来调试。应该用于完整性检查时测试条件是否始终应该为 true,来指示某些程序错误,或者检查具体功能的存在(类似扩展函数或特定的系统限制和功能)。

断言不应该用于普通运行时操作,类似输入参数的检查。作为一个经验法则,在断言禁用时代码也应该能够正确地运行。

assert() 的行为可以通过 assert_options() 来配置,或者手册页面上描述的 .ini 设置。

assert_options() 和/或 ASSERT_CALLBACK 配置指令允许设置回调函数来处理失败的断言。

assert() 回调函数在构建自动测试套件的时候尤其有用,因为它们允许你简易地捕获传入断言的代码,并包含断言的位置信息。 当信息能够被其他方法捕获,使用断言可以让它更快更方便!

回调函数应该接受三个参数。第一个参数包括了断言失败所在的文件。第二个参数包含了断言失败所在的行号,第三个参数包含了失败的表达式(如有任意 — 字面值例如 1 或者 "two" 将不会传递到这个参数)。PHP 5.4.8 及更高版本的用户也可以提供第四个可选参数,如果设置了,用于将 description 指定到 assert()

Expectations(仅 PHP 7)

assert() 是 PHP 7 中的语言结构,允许定义 expectation:断言在开发和测试环境中生效,经过优化,在生产环境中零成本。

出于向后兼容的原因,assert_options() 仍然可以控制如上所述的行为。但仅限 PHP 7 的代码应使用两个新的配置指令来控制 assert() 的行为,而不是调用 assert_options()

用于 assert() 的 PHP 7 控制指令
指令 默认值 可能值
zend.assertions 1
  • 1:生成并执行代码(开发模式)
  • 0:生成代码但在运行时跳转
  • -1:生成代码但在运行时跳转(生产模式)
assert.exception 0
  • 1:断言失败时抛出,抛出提供给 exception 的对象,或未提供 exception 时抛出新的 AssertionError 对象
  • 0:如上所述使用/生成 Throwable,但仅仅是基于该对象生成警告而不是抛出(与 PHP 5 行为兼容)

参数

assertion

断言。在 PHP 5 中,不是要求值的 string 就是要测试的 bool。自 PHP 7 起,可以是任何带返回值的表达式,运行后的结果用于表示断言成功还是失败。

警告

自 PHP 7.2.0 起弃用 string 作为 assertion,自 PHP 8.0.0 起删除。

description

如果 assertion 失败了,选项 description 将会包括在失败信息里。自 PHP 7 起,如果没有提供 description,默认 description 将会提供调用 assert() 的源代码。

exception

在 PHP 7 中,第二个参数可以是 Throwable 对象而不是 descriptive string,如果断言失败且启用 assert.exception 配置指令,会抛出该对象。

返回值

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 不再允许在命名空间中声明叫做 assert() 的函数,并发出 E_COMPILE_ERROR
7.3.0 弃用在命名空间中声明 assert() 函数。这样声明会发出 E_DEPRECATED
7.2.0 弃用使用 string 作为 assertion。当 assert.activezend.assertions 都设为 1 时,现在会发出 E_DEPRECATED 通知。
7.0.0 assert() 现在是语言结构而不是函数。assertion 现在可以是表达式。第二个参数现在解释为 exception(如果给出了 Throwable),或者解释为自 PHP 5.4.8 开始支持的 description

示例

传统断言(PHP 5 和 7)

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

<?php
// 激活断言,并设置它为 quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

//创建处理函数
function my_assert_handler($file, $line, $code)
{
echo
"<hr>Assertion Failed:
File '
$file'<br />
Line '
$line'<br />
Code '
$code'<br /><hr />";
}

// 设置回调函数
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// 让一则断言失败
assert('mysql_query("")');
?>

示例 #2 使用自定义处理器打印描述信息

<?php
// 激活断言,并设置它为 quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// 创建处理函数
function my_assert_handler($file, $line, $code, $desc = null)
{
echo
"Assertion failed at $file:$line: $code";
if (
$desc) {
echo
": $desc";
}
echo
"\n";
}

// 设置回调
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

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

以上示例会输出:

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

Expectations (PHP 7 only)

示例 #3 不带自定义异常的 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

示例 #4 包含自定义异常的 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

参见

add a note add a note

User Contributed Notes 8 notes

up
19
hodgman at ali dot com dot au
14 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
5
mail<at>aaron-mueller.de
16 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
1
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
2
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
-4
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
-7
uramihsayibok, gmail, com
12 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
-2
Ben
6 years ago
if there was no 'warning' message when assertion failed (FALSE), try reset the error handler:
<?php
set_error_handler
( null );
up
-9
office dot stojmenovic at gmail dot com
9 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