Вопрос

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?

Это было полезно?

Решение

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')) { ... }

Другие советы

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.

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)

empty() can only be used to check variables. See the php manual. You can use defined.

if (defined('TEST')) {
    echo TEST;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top