2012-08-23 21 views
0

我有一組php函數,用於在錯誤文本失敗時返回錯誤文本。他們沒有返回文本。我的功能看起來是這樣的:從功能返回的PHP打印字符串

function poop(){ 
    $stuff = stuff; 
    $things = things; 
    if($stuff != stuff){ 
     return 'e: stuff does not equal stuff!'; 
    } 
    if($things != things){ 
     return 'e: things do not equal things!'; 
    } 
    // if we got this far all is good! 
    return true; 

} 

我把我的函數代碼如下所示:

if(poop() === true){ 
    // do things that require poop 
} else { 
    echo poop(); 
} 

我認爲這將返回「E:」字符串作爲一個字符串,並將其打印在頁面poop()沒有返回布爾真值的事件,但事實上並非如此。我想知道這是否是因爲我的代碼的其餘部分的錯誤,或者如果這個功能實際上不存在於PHP中?我應該如何確保我的所有函數檢查都返回錯誤?我應該使用echo而不是return來將它打印成頁面上的一個字符串嗎?

+5

Protip:'foo'或'bar',而不是'poop'。 –

+1

我使用poop作爲變量。 – FrankieTheKneeMan

+2

不明白這個問題,但無論如何你應該做'$ result = poop(); if($ result === true){} else {echo $ result;}'而不是調用func兩次 – tigrang

回答

2

不要多次調用你的函數。在一個變量保存它的返回值:

$ret = poop(); 
if ($ret === true) { 
    // Do things that require the success. 
} else { 
    // Log your error message here: 
    echo "An error occurred: ".$ret; 
    logMessage($ret); 
    // etc. 
} 

您可能還需要尋找到PHP exceptions一個潛在的清潔劑 - 但可能較慢 - 解決錯誤處理。

+0

較短的版本:'if(($ res = poop())=== true){/ ** /} else {echo $ res; }' – inhan

0

試試這個:

if(poop() !== TRUE) 
    echo poop(); 

我用它在此代碼:

function poop(){ 
    $stuff = 'stuff'; 
    $things = 'things'; 
    // this is where we have wrong value 
    if($stuff != 'stuff1'){ 
     return 'e: stuff does not equal stuff!'; 
    } 
    if($things != 'things'){ 
     return 'e: things do not equal things!'; 
    } 
    // if we got this far all is good! 
    return true; 

} 

我希望我goood瞭解你,我在PHP很牛逼了。 :) 這也是一個很好的做法,拋出一個異常,而不是返回錯誤消息字符串。