Can I leave out `if ( ! defined …)` when defining plugin constants?

I’m writing a WordPress plugin. At the top of the plugin file, I define some constants. Can I leave out the if ( ! defined( 'THE_CONSTANT' ) ) tests?

Some other plugins that I’ve studied includes such if ( ! defined tests, some don’t. Personally, I don’t know why my plugin file would ever be included twice?

Read More

The reason I don’t want to include if ( ! defined ... is that I think this is hard to read:
(XYZABC would be the plugin name)

if ( ! defined( 'XYZABC_PLUGIN_BASENAME' ) )
    define( 'XYZABC_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
if ( ! defined( 'XYZABC_SETTINGS_SLUG' ) )
    define( 'XYZABC_SETTINGS_SLUG', 'xyzabc_comments_options' );
if ( ! defined( 'XYZABC_ENABLED_QUERY_PARAM' ) )
    define( 'XYZABC_ENABLED_QUERY_PARAM', 'xyzabc-comments-enabled' );

But this is relatively nice to read:

define( 'XYZABC_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
define( 'XYZABC_SETTINGS_SLUG', 'xyzabc_comments_options' );
define( 'XYZABC_ENABLED_QUERY_PARAM', 'xyzabc-comments-enabled' );

Update:
Workaround.
I defined this function, and then the duplicated-constant-name issue is mostly gone.

function myplugin_define_default($constant_name, $value) {
    if (! defined($constant_name))
        define($constant_name, $value);
}

So now my code looks like so:

define( 'XYZABC_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
xyzabc_define_default( 'XYZABC_SETTINGS_SLUG', 'xyzabc_comments_options' );
xyzabc_define_default( 'XYZABC_ENABLED_QUERY_PARAM', 'xyzabc-comments-enabled' );

Related posts

Leave a Reply

1 comment

  1. By doing the !defined() check you allow earlier code to define that constant before you. This could be useful, for example, if a user is allowed to define its own values for some constants in a file like wp-config.php.

    As for code readability, you may consider using the following one-liner, although you could put a regular if on a single line as well.

    defined('XYZABC_PLUGIN_BASENAME') or define('XYZABC_PLUGIN_BASENAME', 'your_value');