If isset for constants, but not defined?
If I set a constant to = ''
,
defined()
does not do what I want, because it is already defined (as ''
).
isset()
does not work with constants.
开发者_如何学GoIs 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.
精彩评论