我怎样才能检查我的函数print/echo's


How can I check if my function print/echo's something?

我经常使用echo来调试函数代码:

public function MyFunc() {
    // some code...
    echo "OK";
    // some code...
}

我如何检查我的函数print's/echo's的东西?

(伪代码):

MyFunc();
if (<when something was printed>){
    echo "You forgot to delete echo calls in this function";
}

这应该可以为您工作:

只要调用你的函数,当你有输出缓冲并检查内容是否为空,例如

ob_start();
//function calls here
MyFunc();
$content = ob_get_contents();
ob_end_clean();
if(!empty($content))
    echo "You forgot to delete echos for this function";

您可以创建一个$debug标志和一个debuglog()函数,该函数检查调试标志,然后才返回消息。然后,您可以从一个位置切换调试消息的打开和关闭。

define('DEBUGMODE', true); // somewhere high up in a config
function debuglog($msg){
    if( DEBUGMODE ){ echo $msg; }
}

如果你想摆脱你的调试回声,你可以搜索"debuglog("并删除那些代码行。这样,您就不会意外地删除任何在正常执行中需要的echo语句,也不会错过任何应该被删除的调试echo语句。

这是检查是否回显的坏方法。

您可以将名为is_echoes的变量设置为1,或者您可以返回值

public $is_echoed = 0;
//rest
$this->is_echoed = 1;

function myFunc()
{
  return "OK";
}
if(myFunc() == 'OK')
     //rest

您可以使用var_dump()die()来更有效地调试您的代码。

$test = "debud test";
public function MyFunc($test)
{
// some code...
var_dump($test); die();
// some code...
}

参考:http://php.net/manual/en/function.var-dump.php

http://php.net/manual/en/function.die.php

为什么要尝试这样一个广泛的过程来查看某些内容是否已被响应?

对于调试,您绝对可以使用echo来查看在特定用例中是否击中了特定块。但我建议您使用标志并将值返回给调用函数。

function xyz () {
     if (something) return some_value;
     else return some_other_value;
}

当你可以返回一个硬编码的文字时,没有特别需要变量和使用空间来存储0或1。

我建议你使用log4php [1]

但如果没有,我使用这样的函数:

define('DEBUG', true);
function debug($msg){
    if(DEBUG){ echo $msg; }
}

或者像这样在浏览器控制台查看日志:

function debug_to_console( $data ) {
    if ( is_array( $data ) )
        $output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
    else
        $output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
    echo $output;
}