簡體   English   中英

如何檢查我的功能是否打印/回聲?

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

我經常使用echo來調試功能代碼:

public function MyFunc() {

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

}

如何檢查我的函數print / echo是什么?

(偽代碼):

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語句或錯過任何調試回聲語句應該真的被刪除。

檢查某些事情是否得到回應是不好的方法。

您可以將名為is_echoed的變量設置為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這樣的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM