开发者

If isset for constants, but not defined?

开发者 https://www.devze.com 2023-03-15 05:17 出处:网络
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.)

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.

开发者_如何学Go

Is there any simple way ?


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).


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.
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号