assert

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

assert檢查一個斷言是否為 false

說明

PHP 5

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

PHP 7

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

assert() 會檢查指定的 assertion 并在結果為 false 時采取適當的行動。

Traditional assertions (PHP 5 and 7)

如果 assertion 是字符串,它將會被 assert() 當做 PHP 代碼來執(zhí)行。 assertion 是字符串的優(yōu)勢是當禁用斷言時它的開銷會更小,并且在斷言失敗時消息會包含 assertion 表達式。 這意味著如果你傳入了 boolean 的條件作為 assertion,這個條件將不會顯示為斷言函數的參數;在調用你定義的 assert_options() 處理函數時,條件會轉換為字符串,而布爾值 false 會被轉換成空字符串。

斷言這個功能應該只被用來調試。 你應該用于完整性檢查時測試條件是否始終應該為 true,來指示某些程序錯誤,或者檢查具體功能的存在(類似擴展函數或特定的系統(tǒng)限制和功能)。

斷言不應該用于普通運行時操作,類似輸入參數的檢查。 作為一個經驗法則,在斷言禁用時你的代碼也應該能夠正確地運行。

assert() 的行為可以通過 assert_options() 來配置,或者手冊頁面上描述的 .ini 設置。

assert_options() ASSERT_CALLBACK 配置指令允許設置回調函數來處理失敗的斷言。

assert() 回調函數在構建自動測試套件的時候尤其有用,因為它們允許你簡易地捕獲傳入斷言的代碼,并包含斷言的位置信息。 當信息能夠被其他方法捕獲,使用斷言可以讓它更快更方便!

回調函數應該接受三個參數。 第一個參數包括了斷言失敗所在的文件。 第二個參數包含了斷言失敗所在的行號,第三個參數包含了失敗的表達式(如有任意 — 字面值例如 1 或者 "two" 將不會傳遞到這個參數)。 PHP 5.4.8 及更高版本的用戶也可以提供第四個可選參數,如果設置了,用于將 description 指定到 assert()

Expectations (PHP 7 only)

assert() is a language construct in PHP 7, allowing for the definition of expectations: assertions that take effect in development and testing environments, but are optimised away to have zero cost in production.

While assert_options() can still be used to control behaviour as described above for backward compatibility reasons, PHP 7 only code should use the two new configuration directives to control the behaviour of assert() and not call assert_options().

PHP 7 configuration directives for assert()
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 wasn't provided
  • 0: use or generate a Throwable as described above, but only generate a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

參數

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 used to indicate whether the assertion succeeded or failed.

description

如果 assertion 失敗了,選項 description 將會包括在失敗信息里。

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.

返回值

assertion 是 false 則返回 false,否則是 true。

更新日志

版本 說明
7.0.0 assert() is now a language construct and not a function. assertion() can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
5.4.8 增加了參數 descriptiondescription 現在也作為第四個參數提供給 ASSERT_CALLBACK 模式里的回調函數。

范例

Traditional assertions (PHP 5 and 7)

示例 #1 使用自定義處理程序處理失敗的斷言

<?php
// 激活斷言,并設置它為 quiet
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

//創(chuàng)建處理函數
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_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

//創(chuàng)建處理函數
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 without a custom exception

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

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

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

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

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 with a custom exception

<?php
class CustomError extends AssertionError {}

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

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

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

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

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

參見