6

If I set a constant to = '',
How to I check if constant has something inside ?
(ie see if it is set to something other than the empty string.)

defined() does not do what I want, because it is already defined (as '').
isset() does not work with constants.

Is there any simple way ?

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Cameleon
  • 453
  • 1
  • 6
  • 16
  • 3
    You might want to indicate which language you are talking about... – Aasmund Eldhuset Jun 22 '11 at 21:10
  • Oh lol, it seems usual if just do the trick., this can be closed. – Cameleon Jun 22 '11 at 21:14
  • isset wouldnt even help in case of variables because an empty var still is set. isset only drops false it it totally doesnt exist at all, or is NULL. an empty string is still considered set. similar as with defined (the docs dont say it does false on a NULL). – My1 Jul 05 '18 at 11:24

3 Answers3

14

The manual says, that isset() returns whether a "[...] variable is set and is not NULL".

Constants aren't variables, so you can't check them. You might try this, though:

define('FOO', 1);

if (defined('FOO') && 1 == FOO) {
// ....
}

So when your constant is defined as an empty string, you'll first have to check, if it's actually defined and then check for its value ('' == MY_CONSTANT).

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
6

for checking if something is inside you can use (since PHP 5.5) the empty function. to avoid errors I would also check if it is even existing.

if(defined('FOO')&&!empty(FOO)) {
  //we have something in here.
}

since empty also evaluates most false-like expressions (like '0', 0 and other stuff see http://php.net/manual/de/function.empty.php for more) as 'empty'

you can try:

if(defined('FOO') && FOO ) {
  //we have something in here.
}

this should work maybe with more versions (probably everywhere where you can get yoda conditions to run)

for a more strict check you could do:

if(defined('FOO') && FOO !== '') {
  //we have something in here.
}
My1
  • 475
  • 5
  • 21
0

Assuming you assign the constant (and it isn't a system defined constant) use the following:

if(array_key_exists("MY_CONSTANT", get_defined_constants(true)['user'])){
    echo MY_CONSTANT; //do stuff
}

This works because the array result of get_defined_constants(true) is an array all of the defined constants, and anything you define is stored in the sub-array ['user'].

See the manual.

Sablefoste
  • 4,032
  • 3
  • 37
  • 58