分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

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

发布时间:2023-09-06 01:32责任编辑:林大明关键词:PHP

一、前言

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

二、详解

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

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICTdisplay_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 errorsE_RECOVERABLE_ERROR ?- almost fatal run-time errorsE_WARNING ????????- run-time warnings (non-fatal errors)E_PARSE ??????????- compile-time parse errorsE_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 codeE_CORE_ERROR ?????- fatal errors that occur during PHP‘s initial startupE_CORE_WARNING ???- warnings (non-fatal errors) that occur during PHP‘s ???????????????????initial startupE_COMPILE_ERROR ??- fatal compile-time errorsE_COMPILE_WARNING - compile-time warnings (non-fatal errors)E_USER_ERROR ?????- user-generated error messageE_USER_WARNING ???- user-generated warning messageE_USER_NOTICE ????- user-generated notice messageE_DEPRECATED ?????- warn about code that will not work in future versions ???????????????????of PHPE_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 级别的错误。这种情况应该杜绝,规范开发,从基础做起,人人有责!


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

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

原文地址:https://www.cnblogs.com/imayanlong/p/8120070.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved