Have you ever used a function call in empty()
for an if
condition to perform some checking? Then you might come up with an PHP fatal error saying Can’t use method return value in write context. I am explaining here why did the error come and 2 ways to write them correctly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //Output Fatal error: Can't use method return value in write context in (line number) // Code if (empty($res->getError())) // Produces Fatal error { //Do something } //============ Our Function ============ public function getError() { return $this->error; } // Codeigniter Session Example if( empty ($this->session->userdata( 'user_id') ) ) // Produces Fatal error { $error = "ID doesn't exist"; } else { $user_id = $this->session->userdata( 'user_id' ); } |
Reason to error: Can’t use method return value in write context
The reason why do we get the error while using such type of code in PHP versions prior to 5.5 is that empty()
needs to access 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.
In short: empty()
only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name))
. And the same is true for isset()
.
We can write the same code in 2 ways to let them work:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Way One $response = $res->getError(); if (empty($response)) { //Do something } // Way Two if (!$res->getError()) //Note the NOT operator { //Do something } |
And using the second way and by removing NOT operator, we can write our Codeigniter Session Example as follow:
1 2 3 4 5 6 7 8 | if( $this->session->userdata( 'user_id') ) { $user_id = $this->session->userdata( 'user_id' ); } else { $error = "ID doesn't exist"; } |