Can't use method return value in write context

后端 未结 8 1219
野趣味
野趣味 2020-11-22 01:52

I would think the following piece of code should work, but it doesn\'t (Edited: Now works in PHP 5.5+):

if (!empty($r->getError()))


        
相关标签:
8条回答
  • 2020-11-22 02:50

    empty() needs to access the value by reference (in order to check whether that reference points to something that exists), and PHP before 5.5 didn't support references to temporary values returned from functions.

    However, the real problem you have is that you use empty() at all, mistakenly believing that "empty" value is any different from "false".

    Empty is just an alias for !isset($thing) || !$thing. When the thing you're checking always exists (in PHP results of function calls always exist), the empty() function is nothing but a negation operator.

    PHP doesn't have concept of emptyness. Values that evaluate to false are empty, values that evaluate to true are non-empty. It's the same thing. This code:

    $x = something();
    if (empty($x)) …
    

    and this:

    $x = something();
    if (!$x) …
    

    has always the same result, in all cases, for all datatypes (because $x is defined empty() is redundant).

    Return value from the method always exists (even if you don't have return statement, return value exists and contains null). Therefore:

    if (!empty($r->getError()))
    

    is logically equivalent to:

    if ($r->getError())
    
    0 讨论(0)
  • 2020-11-22 02:56

    As pointed out by others, it's a (weird) limitation of empty().

    For most purproses, doing this is equal as calling empty, but this works:

    if ($r->getError() != '')
    
    0 讨论(0)
提交回复
热议问题