檢查一個斷言是否為 false

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 程式碼來執行。 assertion 是字串的優勢是當禁用斷言時它的開銷會更小,並且在斷言失敗時訊息會包含 assertion 表達式。 這意味著如果你傳入了 boolean 的條件作為 assertion,這個條件將不會顯示為斷言函式的參數;在呼叫你定義的 assert_options() 處理函式時,條件會轉換為字串,而布爾值 false 會被轉換成空字串。

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

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

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

//建立處理函式
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);

//建立處理函式
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

參見

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *