PHP 基础篇 - PHP 错误级别详解

一、前言

最近经常看到工作 2 年左右的童鞋写的代码也会出现以静态方法的形式调用非静态方法,这是个 Deprecated 级别的语法错误,代码里不应该出现的。对方很郁闷,说:为什么我的环境可以正常运行呢?

二、详解

代码会不会报错,以及你能不能看到报错信息由 PHP 配置中以下两个参数影响,目前线上主流的配置如下(php.ini 文件中):

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off

下面详细介绍这两个参数:

1. error_reporting

首先来说说 PHP 的错误级别,代码会不会报错由 error_reporting 参数决定,PHP 的错误级别种类如下(点击查看中文版):

E_ALL             - All errors and warnings (includes E_STRICT as of PHP 5.4.0)
E_ERROR           - fatal run-time errors
E_RECOVERABLE_ERROR  - almost fatal run-time errors
E_WARNING         - run-time warnings (non-fatal errors)
E_PARSE           - compile-time parse errors
E_NOTICE          - run-time notices (these are warnings which often result
                    from a bug in your code, but it's possible that it was
                    intentional (e.g., using an uninitialized variable and
                    relying on the fact it is automatically initialized to an
                    empty string)
E_STRICT          - run-time notices, enable to have PHP suggest changes
                    to your code which will ensure the best interoperability
                    and forward compatibility of your code
E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
                    initial startup
E_COMPILE_ERROR   - fatal compile-time errors
E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
E_USER_ERROR      - user-generated error message
E_USER_WARNING    - user-generated warning message
E_USER_NOTICE     - user-generated notice message
E_DEPRECATED      - warn about code that will not work in future versions
                    of PHP
E_USER_DEPRECATED - user-generated deprecation warnings 

其中 WARNING、NOTICE、DEPRECATED 等错误级别会抛出一个错误,但不会终止程序运行。

2. display_errors

再来看一下 display_errors 参数,该参数是是否展示错误信息,只有开启才会显示错误信息(值可以为 on|off、true|false、1|0)。

开发环境最好设置为开启,尽早发现问题,但生产环境一定要关闭。(点击查看中文版官方文档

3. 问题演示

下面使用 PHP 的运行时配置,改变 PHP 的 error_reporting 和 display_errors,演示上面的问题。代码如下:

<?php

// error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);  // 该级别下面的代码不会抛出错误
error_reporting(E_ALL & ~E_NOTICE);
ini_set("display_errors", "on");

class Foo
{
    public function test()
    {
        echo 'test';
    }
}

Foo::test();

运行该代码会输出 test,但同时会抛出一个 Deprecated 级别的错误。这种情况应该杜绝,规范开发,从基础做起,人人有责!


本文首发于马燕龙个人博客,欢迎分享,转载请标明出处。
马燕龙个人博客:https://www.mayanlong.com
马燕龙个人微博:http://weibo.com/imayanlong
马燕龙Github主页:https://github.com/yanlongma

标签: none

不错,不错,对我有帮助! 我要打赏他!GO ->

添加新评论