Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am seeing many plugins use the following format for defining their constant:

/* Set the constant path to the plugin's javascript directory. */
if( !defined( 'MY_ETS_JS' ) )
    define( 'MY_ETS_JS', MY_ETS_URI . trailingslashit( 'js' ), true );    

So basically there is a check before we define the constant.

My question is why is this check necessary? What if I make a new version of the plugin and want to change the name of the javascript folder from 'js' to 'javascript'? I would have to include that change in an upgrade routine. Why not just define the constants without checking for their existence?

share|improve this question
    
Defined is used to check whether a given named constant exists and not global variable. php.net/manual/en/function.defined.php –  Vinod Dalvi Mar 5 '13 at 10:30
    
you would use isset, but this is basic PHP, not WordPress, read up on php.net and ask on stackoverflow if it continues to give you problems –  Tom J Nowell Mar 5 '13 at 12:43

2 Answers 2

up vote 4 down vote accepted

These are not PHP global variables, they are constants that cannot be modified(hence the name).

Trying to redefine them, using a define() will trigger a notice since they are already defined(and consequently keep the initial value assigned). To stay away from notices, you should check if they have been defined() before.

Example:

define('VARIABLE', 'hello');
define('VARIABLE', 'world');
echo VARIABLE;

Results:

Notice: Constant VARIABLE already defined in **your-file** on line xxx
hello

In this case the variable won't be updated to world.

Example using defined():

define('VARIABLE', 'hello');

if(!defined('VARIABLE')){
  define('VARIABLE', 'world');
}
else{
  echo "VARIABLE HAS ALREADY BEEN DEFINED.<br />";
}
echo VARIABLE;

Results:

VARIABLE HAS ALREADY BEEN DEFINED.
hello

In this case you can specify an action to perform in case that constant has already been defined.

share|improve this answer

You cannot re-define defines. They're called constants. So this is more a check to not produce an error.

You either have to set a new define, or use a define, that in turn uses some dynamical part (i.e., a variable).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.