是否可以写入字符串或日志到控制台?

我的意思是

就像在JSP中一样,如果我们打印system.out.println("some")这样的东西,它将出现在控制台,而不是页面上。


当前回答

我正在寻找一种方法来调试我正在开发的WordPress插件中的代码,然后看到了这篇文章。

我从其他回复中选取了最适合我的代码,并将它们组合成一个函数,我可以用它来调试WordPress。函数为:

function debug_log($object=null, $label=null, $priority=1) {
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}

用法如下:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);

如果这个函数用于WordPress开发,那么这个函数应该放在子主题的functions.php文件中,然后可以在代码的任何地方调用。

其他回答

我发现这很有帮助:

function console($data, $priority, $debug)
{
    if ($priority <= $debug)
    {
        $output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';

        echo $output;
    }
}

像这样使用它:

<?php
    $debug = 5; // All lower and equal priority logs will be displayed
    console('Important', 1 , $debug);
    console('Less Important', 2 , $debug);
    console('Even Less Important', 5 , $debug);
    console('Again Important', 1 , $debug);
?>

在控制台输出:

重要的 不那么重要 更不重要 同样重要的

您可以通过使用$debug值限制不太重要的日志来关闭它们。

默认情况下,所有输出都输出到stdout,即HTTP响应或控制台,这取决于脚本是由Apache运行还是在命令行上手动运行。但是您可以使用error_log进行日志记录,并且可以使用fwrite写入各种I/O流。

我已经放弃了上述所有工具,转而使用调试器和记录器。我怎么称赞都不为过!

只需点击右上角的一个标签,或者点击“点击这里”来展开/隐藏。

注意不同的“类别”。您可以单击任意数组展开/折叠它。

从网页

主要特点: 显示全局变量($ globals, $_POST, $_GET, $_COOKIE等) 显示PHP版本和加载的扩展 替换PHP内置的错误处理程序 记录SQL查询 监视代码和SQL查询的执行时间 检查变量的变化 函数调用跟踪 代码覆盖分析,检查执行了哪些脚本行 转储所有类型的变量 文件检查器与代码高亮显示查看源代码 发送消息到JavaScript控制台(仅限Chrome),用于Ajax脚本

作为热门答案中链接网页的作者,我想添加我最后一个版本的这个简单的助手功能。它更坚固。

我使用json_encode()来检查变量类型是否不必要,并添加一个缓冲区来解决框架的问题。header()没有稳定的返回或者使用过多。

/**
 * Simple helper to debug to the console
 *
 * @param $data object, array, string $data
 * @param $context string  Optional a description.
 *
 * @return string
 */
function debug_to_console($data, $context = 'Debug in Console') {

    // Buffering to solve problems frameworks, like header() in this and not a solid return.
    ob_start();

    $output  = 'console.info(\'' . $context . ':\');';
    $output .= 'console.log(' . json_encode($data) . ');';
    $output  = sprintf('<script>%s</script>', $output);

    echo $output;
}

使用

// $data is the example variable, object; here an array.
$data = [ 'foo' => 'bar' ];
debug_to_console($data);`

结果截图

另外,一个简单的例子作为一个图像,更容易理解它:

这两个都有效:

<?php
    $five = 5;
    $six = 6;
?>
<script>
    console.log(<?php echo $five + $six ?>);
</script>


<?php
    $five = 5;
    $six = 6;
    echo("<script>console.log($five + $six);</script>");
?>