Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If isset for constants, but not defined?

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 ?

like image 674
Cameleon Avatar asked Jun 22 '11 21:06

Cameleon


People also ask

How do you check whether a constant is defined or not in PHP?

Checking if a PHP Constant is Defined This can be achieved using the PHP defined() function. The defined() function takes the name of the constant to be checked as an argument and returns a value of true or false to indicate whether that constant exists.

What is if isset ($_ POST?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Does Isset check for empty?

empty() function in PHP ? The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.

How check array is set or not in PHP?

The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.


2 Answers

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

like image 100
Linus Kleen Avatar answered Sep 18 '22 18:09

Linus Kleen


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.
}
like image 34
My1 Avatar answered Sep 20 '22 18:09

My1