繁体   English   中英

php打印字符串从函数返回

[英]php print string returned from function

我有一组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来将其作为字符串打印在页面上吗?

不要多次调用您的函数。 将其返回值保存在变量中:

$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异常 ,以寻找可能更清晰但可能更慢的错误处理解决方案。

尝试这个:

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; 

}

我希望我能理解你,我也是PHP的新手。 :)抛出异常而不是返回错误消息msg字符串也是一种好习惯。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM