assert

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

assert檢查一個(gè)斷言是否為 false

說明

PHP 5

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

PHP 7

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

assert() 會(huì)檢查指定的 assertion 并在結(jié)果為 false 時(shí)采取適當(dāng)?shù)男袆?dòng)。

Traditional assertions (PHP 5 and 7)

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

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

斷言不應(yīng)該用于普通運(yùn)行時(shí)操作,類似輸入?yún)?shù)的檢查。 作為一個(gè)經(jīng)驗(yàn)法則,在斷言禁用時(shí)你的代碼也應(yīng)該能夠正確地運(yùn)行。

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

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

assert() 回調(diào)函數(shù)在構(gòu)建自動(dòng)測(cè)試套件的時(shí)候尤其有用,因?yàn)樗鼈冊(cè)试S你簡(jiǎn)易地捕獲傳入斷言的代碼,并包含斷言的位置信息。 當(dāng)信息能夠被其他方法捕獲,使用斷言可以讓它更快更方便!

回調(diào)函數(shù)應(yīng)該接受三個(gè)參數(shù)。 第一個(gè)參數(shù)包括了斷言失敗所在的文件。 第二個(gè)參數(shù)包含了斷言失敗所在的行號(hào),第三個(gè)參數(shù)包含了失敗的表達(dá)式(如有任意 — 字面值例如 1 或者 "two" 將不會(huì)傳遞到這個(gè)參數(shù))。 PHP 5.4.8 及更高版本的用戶也可以提供第四個(gè)可選參數(shù),如果設(shè)置了,用于將 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)

參數(shù)

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 失敗了,選項(xiàng) description 將會(huì)包括在失敗信息里。

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 增加了參數(shù) description。 description 現(xiàn)在也作為第四個(gè)參數(shù)提供給 ASSERT_CALLBACK 模式里的回調(diào)函數(shù)。

范例

Traditional assertions (PHP 5 and 7)

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

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

//創(chuàng)建處理函數(shù)
function my_assert_handler($file$line$code)
{
    echo 
"<hr>Assertion Failed:
        File '
$file'<br />
        Line '
$line'<br />
        Code '
$code'<br /><hr />";
}

// 設(shè)置回調(diào)函數(shù)
assert_options(ASSERT_CALLBACK'my_assert_handler');

// 讓一則斷言失敗
assert('mysql_query("")');
?>

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

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

//創(chuàng)建處理函數(shù)
function my_assert_handler($file$line$code$desc null)
{
    echo 
"Assertion failed at $file:$line$code";
    if (
$desc) {
        echo 
": $desc";
    }
    echo 
"\n";
}

// 設(shè)置回調(diào)函數(shù)
assert_options(ASSERT_CALLBACK'my_assert_handler');

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

以上例程會(huì)輸出:

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

參見