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

查看:35
本文介绍了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?

推荐答案

种类.您可以在 error 中激活 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天全站免登陆