簡述
編寫代碼時,我們總是會做出一些假設,斷言就是用於在代碼中捕捉這些假設,可以將斷言看作是異常處理的一種高級形式。程序員斷言在程序中的某個特定點該的表達式值為真。如果該表達式為假,就中斷操作。
可以在任何時候啟用和禁用斷言驗證,因此可以在測試時啟用斷言,而在部署時禁用斷言。同樣,程序投入運行后,最終用戶在遇到問題時可以重新起用斷言。
使用斷言可以創建更穩定,品質更好且不易於出錯的代碼。單元測試必須使用斷言!
PHP斷言
# PHP5
bool assert ( mixed $assertion [, string $description ] )
# PHP7
bool assert ( mixed $assertion [, Throwable $exception ] )
example1:
// 斷言操作選項函數
assert_options(ASSERT_ACTIVE, 1); // 默認是打開斷言的
assert('1==2'); // Warning: assert(): Assertion "1==2" failed in D:\wamp\www\XF9_Trunk_Website3.0\new\Public\index.php on line 3
echo 555555555555; // 默認情況下繼續執行,對於調試很好,尤其是可以使用callback,但是生產環境就不建議使用了。
assert() 會檢查指定的 assertion 並在結果為 FALSE 時采取適當的行動(視assert_options而定)。
assert_options
'ASSERT_ACTIVE=1' // Assert函數的開關
'ASSERT_WARNING =1' // 當表達式為false時,是否要輸出警告性的錯誤提示,issue a PHP warning for each failed assertion
'ASSERT_BAIL= 0' // 是否要中止運行;terminate execution on failed assertions
'ASSERT_QUIET_EVAL= 0' // 是否關閉錯誤提示,在執行表達式時;disable error_reporting during assertion expression evaluation
'ASSERT_CALLBACK= (NULL)' // 是否啟動回調函數 user function to call on failed assertions
// Active 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 "
Assertion Failed:File '$file'
Line '$line'
Code '$code'
";
}
// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Make an assertion that should fail
assert('mysql_query("")');
安全性
function fo(){
file_put_contents('a.php','www.bo56.com');
return true;
}
$func = $_GET["func"];
assert("$func()");
如果 assertion 是字符串,它將會被 assert() 當做 PHP 代碼來執行。跟eval()類似, 不過eval($assertion)只是執行符合php編碼規范的$code_str。