0

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?

2
  • Defined is used to check whether a given named constant exists and not global variable. php.net/manual/en/function.defined.php Commented Mar 5, 2013 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
    Commented Mar 5, 2013 at 12:43

2 Answers 2

6

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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