jan*_*mon 61 php variables declaration
其他具有自动变量声明的语言(如Perl)具有严格模式.
通过激活此严格模式,需要变量声明,并且只要您尝试使用未声明的变量,Perl就会抛出错误.
PHP提供任何类似的功能吗?
Pek*_*ica 65
的种类.您可以E_NOTICE在错误报告中激活级别.(这里的常量列表.)
使用未声明变量的每个实例都会抛出一个E_NOTICE.
该E_STRICT错误livel也将使你的通知,以及关于如何优化代码的其他提示.
error_reporting(E_STRICT);
Run Code Online (Sandbox Code Playgroud)
终止脚本
如果你真的很认真,并希望你的脚本终止而不是只是在遇到未声明的变量时输出通知,你可以构建一个自定义错误处理程序.
仅处理其中带有"未定义变量"的NOTICE并将其他所有内容传递给默认PHP错误处理程序的工作示例:
<?php
error_reporting(E_STRICT);
function terminate_missing_variables($errno, $errstr, $errfile, $errline)
{
if (($errno == E_NOTICE) and (strstr($errstr, "Undefined variable")))
die ("$errstr in $errfile line $errline");
return false; // Let the PHP error handler handle all the rest
}
$old_error_handler = set_error_handler("terminate_missing_variables");
echo $test; // Will throw custom error
xxxx(); // Will throw standard PHP error
?>
Run Code Online (Sandbox Code Playgroud)
Gor*_*don 40
使用
error_reporting(-1);
Run Code Online (Sandbox Code Playgroud)
显示每个可能的错误,包括E_STRICT甚至在将来的PHP版本中添加新的级别和常量时.
(参考)
几年后,PHP 7.0.0获得了 declare(strict_types=1);
http://php.net/manual/zh-CN/functions.arguments.php#functions.arguments.type-declaration.strict
| 归档时间: |
|
| 查看次数: |
54307 次 |
| 最近记录: |