Reputation: 16061
Why does
if (!empty(constant('MY_CONST')))
throw this error
Fatal error: Can't use function return value in write context
and how do I work around it?
Upvotes: 1
Views: 1468
Reputation: 7821
With PHP 5.5.0 your code will work as is. However, you can simply break your statement into 2 pieces for backward compatibility.
$a = constant('MY_CONST');
if(!empty($a)) { //do something }
Alternatively, you can use the defined()
function.
Upvotes: 2
Reputation: 223
empty() can only be used to check variables. See the php manual. You can use defined.
if (defined('TEST')) {
echo TEST;
}
Upvotes: 0
Reputation: 78443
It's due to implementation details in PHP: until PHP 5.4.x, only variables can be tested using empty()
.
What you're trying to do will likely work in php 5.5. Alternatively, use:
if (defined('CONST') && CONST)
Upvotes: 0
Reputation: 8587
See the note here:
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 you should rather compare against null
as constant()
will return null
for undefined constants, or use defined()
instead.
if(constant('MY_CONST')!==null) { ... }
if(!defined('MY_CONST')) { ... }
Upvotes: 5