Can’t use function return value in write context

  1. PHP logo

Did you ever develop some nice code, then simply wanted to check if a string was only composed of white spaces or tabs, and used something like this:

if (!empty(trim($string))) { ... }

…only to get a bad error appear (only on your PHP 5.4 server) in the middle of your app, like this?:

Fatal error: Can't use function return value in write context

Well, this has a simple explanation…

Prior to PHP 5.5, the empty() function did not accept something else than a variable. From php.net/empty:

Note:

Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

So the easy solution (but kind of making PHP feel beyond help) is to do what is recommended in the comment (trim($string) == false) or decompose your statement (although it will be less efficient than the above):

$string = trim($string);
if (!empty($string)) { ... }

This is due to the fact that empty() is a language construct, not really a function (it works as a function to make things easier). So, under the same logic, this will not work with other language constructs, like echo, require, etc (although the explanation in empty’s documentation is clearer than any other).

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *