PHP Fatal error: Can’t use method return value in write context
I came across the following error recently when trying to evaluate in PHP whether a value was empty:
Fatal error: Can't use method return value in write context
It turns out that the PHP empty function cannot accept the return value from another function so you have to first define the variable before passing it to the empty() function.
// will generate a fatal error empty(nl2br($string)); empty($obj->getSomeValue()); // will work $val = nl2br($string); $val = $obj->getSomeValue(); empty($val);
Alternatively, you can use the following function instead:
/**
* Determines whether a variable is considered to be empty,
* additionally accepts returned values from functions
*
* @param mixed $val The value to evaluate
* @return boolean
*/
function empty_return($val) {
return empty($val);
}
// example
empty_return(nl2br($string));
Categories: PHP
Since the empty() function uses the same rules as casting a variable to a boolean (it returns true only if PHP would treat a variable as false), you can use a boolean “not” as an alternative; in your example:
! nl2br($string)
The one advantage given in the manual (that it will not warn on unset variables) is irrelevant, since you are not using a variable (which is why you couldn’t use empty() in the first place).