Can't use method return value in write context

后端 未结 8 1234
野趣味
野趣味 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:34

    I usually create a global function called is_empty() just to get around this issue

    function is_empty($var)
    { 
     return empty($var);
    }
    

    Then anywhere I would normally have used empty() I just use is_empty()

    0 讨论(0)
  • 2020-11-22 02:35

    The issue is this, you want to know if the error is not empty.

    public function getError() {
        return $this->error;
    }
    

    Adding a method isErrorSet() will solve the problem.

    public function isErrorSet() {
        if (isset($this->error) && !empty($this->error)) {
            return true;
        } else {
            return false;
        }
    }
    

    Now this will work fine with this code with no notice.

    if (!($x->isErrorSet())) {
        echo $x->getError();
    }
    
    0 讨论(0)
  • 2020-11-22 02:36

    I'm not sure if this would be a common mistake, but if you do something like:

    $var = 'value' .= 'value2';
    

    this will also produce the same error

    Can't use method return value in write context

    You can't have an = and a .= in the same statement. You can use one or the other, but not both.

    Note, I understand this is unrelated to the actual code in the question, however this question is the top result when searching for the error message, so I wanted to post it here for completeness.

    0 讨论(0)
  • 2020-11-22 02:39

    The alternative way to check if an array is empty could be:

    count($array)>0
    

    It works for me without that error

    0 讨论(0)
  • 2020-11-22 02:47

    Prior to PHP 5.5, the the PHP docs used to say:

    empty() only checks variables as anything else will result in a parse error

    In PHP < 5.5 you weren't able use empty() directly on a function's return value. Instead, you could assign the return from getError() to a variable and run empty() on the variable.

    In PHP >= 5.5 this is no longer necessary.

    0 讨论(0)
  • 2020-11-22 02:48

    Note: This is a very high voted answer with a high visibility, but please note that it promotes bad, unnecessary coding practices! See @Kornel's answer for the correct way.

    Note #2: I endorse the suggestions to use @Kornel's answer. When I wrote this answer three years ago, I merely meant to explain the nature of the error, not necessarily endorse the alternative. The code snippet below is not recommended.


    It's a limitation of empty() in PHP versions below 5.5.

    Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

    You'd have to change to this

    // Not recommended, just illustrates the issue
    $err = $r->getError();
    if (!empty($err))
    
    0 讨论(0)
提交回复
热议问题