简体   繁体   English

php打印字符串从函数返回

[英]php print string returned from function

I have a set of php functions designed to return error text if they fail. 我有一组php函数,如果失败则返回错误文本。 They aren't returning the text. 他们没有退回文本。 My function looks like this: 我的功能看起来像这样:

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;

}

I call my function in code like so: 我在代码中调用我的函数是这样的:

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

I thought this would return the 'e:' string as a string and print it to the page in the event that poop() did not return a boolean true value, but in reality it is not. 我认为这会将'e:'字符串作为字符串返回并在poop()没有返回布尔值的情况下将其打印到页面,但实际上并非如此。 I'm wondering if this is because of a fault in the remainder of my code or if this functionality doesn't actually exist in PHP? 我想知道这是因为我的代码的其余部分是否有错误,或者PHP中是否实际存在此功能? How should I go about ensuring I have an error returned from all my function checks? 我该如何确保从所有功能检查中返回错误? Should I use echo instead of return to print it as a string on the page? 我应该使用echo而不是return来将其作为字符串打印在页面上吗?

Don't call your function more than once. 不要多次调用您的函数。 Save its return value in a variable: 将其返回值保存在变量中:

$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.
}

You may also want to look into PHP exceptions for a potentially cleaner — but probably slower — solution to error handling. 您可能还希望查看PHP异常 ,以寻找可能更清晰但可能更慢的错误处理解决方案。

try this: 尝试这个:

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

I used it on this code: 我在这段代码上使用它:

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; 

}

I hope I goood understood you, I'm newby in PHP too. 我希望我能理解你,我也是PHP的新手。 :) It is also good practice to throw an exception instead of returning error msg string. :)抛出异常而不是返回错误消息msg字符串也是一种好习惯。

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

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