Heim  >  Artikel  >  Backend-Entwicklung  >  利用浏览器的Javascript控制台调试PHP程序_php技巧

利用浏览器的Javascript控制台调试PHP程序_php技巧

WBOY
WBOYOriginal
2016-05-17 08:51:36959Durchsuche

PHP是一种服务器端脚本语言,用来开发动态web应用程序。与JAVA相比,没有一个好的服务器端调试工具是其限制之一。通常我们都是在PHP代码中添加echo、var_dump等语句,将变量、数组的值显示在浏览器中来达到调试的目的。

现在,越来越多的浏览器都有了开发这工具或者Javascript控制台,通过这些工具,我们可以很方便的显示PHP代码中的变量或数组值。下面我们来做一个例子。例子中的PHP代码有四个跟踪级别:info, warn, log, error,开发人员可以使用浏览器控制台来显示错误变量,数组值。

将下面代码拷贝到PHP文件中,并保存为WebConsole.php

复制代码 代码如下:

class WebConsole {

private static function write($data, $type = 'info') {
$method_types = array('error', 'info', 'log', 'warn');
$msg_type = '';(PS:T不错的PHP Q扣峮:304224365,验证:csl)
if(in_array($type, $method_types)) {
$msg_type = sprintf("console.%s", $type);
}else {
$msg_type = sprintf("console.%s", 'info');
}

if(is_array($data)) {
echo("<script>$msg_type('".implode(', ', $data)."');</script>");
} else {
echo("<script>$msg_type('".$data."');</script>");
}
}

public static function info($data) {
self::write($data);
}

public static function error($data) {
self::write($data, 'error');
}

public static function log($data) {
self::write($data, 'log');
}

public static function warn($data) {
self::write($data, 'warn');
}

}
?>

现在,导入WebConsole类,并使用跟踪功能。
复制代码 代码如下:

require_once('WebConsole.php');
$fruits = array('apple', 'mange', 'banana');
WebConsole::log($fruits);
WebConsole::info($fruits);
WebConsole::warn($fruits);
WebConsole::error($fruits);
?>

现在打开你的浏览器控制台,你会发现出现类似下面的屏幕截图:
利用浏览器的Javascript控制台调试PHP程序_php技巧
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn