In PHP, why does “or die()” work, but “or return” doesn't?

后端 未结 3 820
我在风中等你
我在风中等你 2021-02-18 18:26

In PHP, you can handle errors by calling or die to exit when you encounter certain errors, like this:

$handle = fopen($location, \"r\") or die(\"Cou         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 18:53

    Return is fairly special - it cannot be anything like a function since it's a tool to exit functions. Imagine this:

    if(1==1) return();  // say what??
    

    If it was like this, return would have to be a function that does a "double exit", leaving not just its own scope but the caller's, too. Therefore return is nothing like an expression, it simply can't work that way.

    Now in theory, return could be an expression that evaluates to (say) false and then quits the function; maybe a later php version will implement this.

    The same thing applies to goto which would be a charm to work as a fallback; and yes, fallbacks are necessary and often make the code readable, so if someone complains about "clever code" (which certainly is a good point) maybe php should have some "official" way to do such a thing:

    connectMyDB() fallback return false;
    

    Something like try...catch, just more to the point. And personally, I'd be a lot happier with "or" doing this job since it's working well with English grammar: "connect or report failure".

    TLDR: you're absolutely right: return, goto, break - none of them works. Easy to understand why but still annoying.

提交回复
热议问题