PHP中的严格模式 [英] Strict mode in PHP

查看:251
本文介绍了PHP中的严格模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他具有自动变量声明的语言(例如Perl)具有严格的模式.

Other languages with automatic variable declaration - like Perl - have a strict mode.

通过激活此严格模式,需要变量声明,并且当您尝试使用未声明的变量时,Perl会引发错误.

By activating this strict mode, variable declaration is required, and Perl throws an error as soon as you try to use an undeclared variable.

PHP提供类似的功能吗?

Does PHP offer a similar feature?

推荐答案

种类.您可以在错误报告中激活E_NOTICE级别. . (常量列表此处.)

Kind of. You can activate the E_NOTICE level in your error reporting. (List of constants here.)

使用未声明变量的每个实例都会抛出一个E_NOTICE.

Every instance of usage of an undeclared variable will throw an E_NOTICE.

E_STRICT错误级别也将引发这些通知,以及有关如何优化代码的其他提示.

The E_STRICT error level will also throw those notices, as well as other hints on how to optimize your code.

error_reporting(E_STRICT);

终止脚本

如果您真的很认真,并且想让脚本终止,而不是在遇到未声明的变量时仅输出通知,则可以构建

If you are really serious, and want your script to terminate instead of just outputting a notice when encountering an undeclared variable, you could build a custom error handler.

一个工作示例,仅处理其中带有未定义变量"的E_NOTICE,并将其他所有内容传递给默认的PHP错误处理程序:

A working example that handles only E_NOTICEs with "Undefined variable" in them and passes everything else on to the default PHP error handler:

<?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

 ?>

这篇关于PHP中的严格模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆