如何检查我的功能是否打印/回声?

时间:2015-07-10 09:37:25

标签: php function echo

我经常使用echo来调试功能代码:

public function MyFunc() {

    // some code...
    echo "OK";
    // some code...

}

如何查看我的功能是否打印了/回声?

(伪代码):

MyFunc();

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

6 个答案:

答案 0 :(得分:36)

这应该适合你:

output buffering开启的同时调用您的函数,然后检查内容是否为空,例如。

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";

答案 1 :(得分:16)

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

define('DEBUGMODE', true); // somewhere high up in a config

function debuglog($msg){
    if( DEBUGMODE ){ echo $msg; }
}

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

答案 2 :(得分:2)

检查某些内容是否得到回应是不好的方法。

您可以将名为is_echoed的变量设置为1,也可以返回值

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

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

答案 3 :(得分:1)

您可以使用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

答案 4 :(得分:1)

为什么你想尝试这样一个广泛的过程,看看是否有回音的东西?

对于调试,你肯定可以使用echo来查看在特定用例期间是否正在命中特定块。但我建议你使用标志并将值返回给调用函数。

function xyz () {

     if (something) return some_value;
     else return some_other_value;
}

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

答案 5 :(得分:0)

我建议您使用log4php [1]

之类的内容

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

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

或类似的内容,以查看log in the browser控制台:

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;
}
相关问题