在 PHP7 中為了提高執(zhí)行效率,引入了一個新的功能,即在函數(shù)方法中增加了 Scalar 類型聲明(標量類型聲明),這樣做節(jié)省了對數(shù)據(jù)類型的檢測。標量類型聲明有如下的兩個選項:
可以使用上述模式強制執(zhí)行以下類型的函數(shù)參數(shù):
<?php
// Coercive mode
function sum(int ...$ints) {
return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
運行上述代碼,它產(chǎn)生以下瀏覽器輸出:
9
<?php
// Strict mode
declare(strict_types=1);
function sum(int ...$ints) {
return array_sum($ints);
}
print(sum(2, '3', 4.1));
?>
運行上述代碼,它產(chǎn)生以下瀏覽器輸出:
PHP Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in /soft/node/run.php on line 7 and defined in /soft/node/run.php:4 Stack trace: #0 /soft/node/run.php(7): sum(2, '3', 4.1) #1 {main} Next TypeError: Argument 3 passed to sum() must be of the type integer, float given, called in /soft/node/run.php on line 7 and defined in /soft/node/run.php:4 Stack trace: #0 /soft/node/run.php(7): sum(2, '3', 4.1) #1 {main} thrown in /soft/node/run.php on line 4
嚴格模式的校驗行為:嚴格的類型校驗調(diào)用拓展或者 PHP 內(nèi)置函數(shù),會改變 zend_parse_parameters 的行為。特別注意,失敗的時候,它會產(chǎn)生E_RECOVERABLE_ERROR 而不是E_WARNING。嚴格類型校驗規(guī)則是非常直接的:只有當類型和指定類型聲明匹配,它才會接受,否則拒絕。
更多建議: