## 簡述
編寫代碼時,我們總是會做出一些假設,斷言就是用于在代碼中捕捉這些假設,可以將斷言看作是異常處理的一種高級形式。**程序員斷言在程序中的某個特定點該的表達式值為真。如果該表達式為假,就中斷操作**。
可以在任何時候啟用和禁用斷言驗證,因此可以在測試時啟用斷言,而在部署時禁用斷言。同樣,程序投入運行后,最終用戶在遇到問題時可以重新起用斷言。
使用斷言可以創建更穩定,品質更好且不易于出錯的代碼。單元測試必須使用斷言!
## 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 "<hr>Assertion Failed:File '$file'<br />Line '$line'<br />Code '$code'<br /><hr />";
}
// 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。
## PHP7中的斷言
向后兼用并增強之前的 assert() 的方法。 它使得在生產環境中啟用斷言為零成本,并且提供當斷言失敗時拋出特定異常的能力。
```php
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(2 == 1, new CustomError('Some error message'));
```
- 現代化PHP特性
- php7常用特性整理
- 反射機制Reflection
- 依賴注入與服務容器
- 抽象類與接口
- 類多繼承的替代方案Traits
- 類的延遲綁定(后期綁定)
- 生成器語法
- 匿名函數和閉包
- 匿名類
- 理解php的output buffer
- 斷言ASSERT
- 魔術方法小結
- Zend Opcache字節碼緩存
- 內置的http服務器
- SPL標準庫
- 【SPL標準庫專題(1)】SPL簡介
- 【SPL標準庫專題(2)】Iterator
- 【SPL標準庫專題(3)】Classes
- 【SPL標準庫專題(4)】Exceptions
- 【SPL標準庫專題(5)】Datastructures:SplDoublyLinkedList
- 【SPL標準庫專題(6)】Datastructures:SplStack & SplQueue
- 【SPL標準庫專題(7)】Datastructures:SplPriorityQueue
- 【SPL標準庫專題(8)】Datastructures:SplHeap & SplMaxHeap & SplMinHeap
- 【SPL標準庫專題(9)】Datastructures:SplFixedArray
- 【SPL標準庫專題(10)】Datastructures:SplObjectStorage
- PHPcomposer使用手札[ing]
- PHP中的多態
- 通過命名空間實現自動加載的框架雛形
- 日期與金額
- PHPstorm使用攻略
- 筆記本