首页 > 开发 > PHP > 正文

调试PHP程序的多种方法介绍

2024-05-04 22:17:55
字体:
来源:转载
供稿:网友

调试的定义:通过一定方法,在程序中找到并减少缺陷的数量,从而使其能正常工作。
这里说一些如何调试PHP程序的经验。

一、PHP自带的调试功能

1、自带的报错功能

两个名词:开发环境是开发人员在进行开发和调试的环境,生产环境是最终客户在用的线上环境;
开发环境和生产环境要分开设置报错功能。

(1)开发环境

开发环境需要打开报错,以下是php.ini的配置项及其说明:
代码如下:
; This directive sets the error reporting level.
; Development Value: E_ALL | E_STRICT (Show all errors, warnings and notices including coding standards.)
error_reporting = E_ALL | E_STRICT

; This directive controls whether or not and where PHP will output errors,
; notices and warnings too. Error output is very useful during development.
; Development Value: On
display_errors = On

这样你在开发过程中,能第一时间发现错误。

即使是一个低等级的报错“Notice: Undefined variable: a in E:/phpspace/test.php on line 14”,但一个未定义的变量的使用往往暗藏着bug。

你会问,如果我引进了开源的类库,他们抛出一堆的低等级错误怎么办?一般代码质量好的类库,也没有“Notice”级别的报错的。所以这也是鉴别一个类库质量的方法。

(2)生产环境

生产环境不能直接将错误输出,而是记入日志,以下是php.ini的配置项及其说明:
代码如下:
; It could be very dangerous in production environments.
; It's recommended that errors be logged on production servers rather than
; having the errors sent to STDOUT.
display_errors = Off

; Besides displaying errors, PHP can also log errors to locations such as a
; server-specific log, STDERR, or a location specified by the error_log
; directive found below. While errors should not be displayed on productions
; servers they should still be monitored and logging is a great way to do that.
; Production Value: On
log_errors = On

; Log errors to specified file.
error_log = /path/to/php_error.log

当然日志写到文件里只是一个选择,还有其他配置可参考手册。

生产环境是给客户提供服务的,你不可能在上面进行断点、打印输出等操作,所以日志是不错的选择。

2、其他一些语言特性、功能的使用

(1)少用错误控制运算符“@”

其的作用是,将“@”放置在一个PHP表达式之前,该表达式可能产生的任何错误信息都被忽略掉。

如果一个缺陷发生在这个表达式中,从PHP的输出中看不到任何错误,这增加了调试的难度。所以能不用则不用。

(2)有些函数自带有debug功能

比如这行代码:
代码如下:
$fp = fsockopen(“www.example.com”, 80, $errno, $errstr, 30);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表