Home / How to tell if a PHP constant has been defined already

How to tell if a PHP constant has been defined already

You can define constants in PHP with the define() function and can check if a constant has already been defined with the defined() function. This post looks at both functions with some examples.

Defining a constant with PHP

Before showing some examples of checking if a constant has been defined with PHP we’ll briefly look at how to define a constant first. This is done with the define() function where the first parameter passed is the name of the constant and the second parameter the value.

The following example sets the constant FOO with the value ‘bar’. Constant names do not have to be uppercase but the naming convention means they usually are:

define('FOO', 'bar');

Note the constant name is enclosed with quotes. Without the quotes you are actually passing a constant to the function instead of the name, and will generate a notice type error mesage if that constant has not already been defined like so:

PHP Notice:  Use of undefined constant FOO - assumed 'FOO' in ...

If the constant FOO has not already been defined then it will actually define a constant with the name FOO anyway; this is undesirable behaviour and may have unexpected consequences depending if the constant had already been defined or not, so make sure you always use either single quotes or double quotes when defining the name of the constant.

Notice error if a constant is defined twice

If you attempt to define a constant twice in PHP you will get a notice type error message. The following example attempts to define FOO twice:

define('FOO', 'bar');
define('FOO', 'bar');

And you will get an error message like so:

PHP Notice:  Constant FOO already defined in ...

Checking to see if a constant has been defined with PHP

Checking to see if a function has already been defined in PHP is done using the defined() function which works in a similar way to the define() function. A single parameter is passed in which again needs to be a single or double quoted string.

To test if FOO has been defined and to take appropriate action, you could do something like this:

if(defined('FOO')) {
    // do something when it is defined
else {
    // do something else because it isn't

To do something only if FOO hasn’t been defined you could do this:

if(!defined('FOO')) {
    // do something because it's not defined

And finally, to test to see if the constant FOO has been defined and define it if it hasn’t, do this:

if(!defined('FOO')) {
    define('FOO', 'bar');

Future posts

In next Monday’s post I’ll look at how to specify a custom error handler for the PHP ADODB Lite database abstraction library. This involves the use of defining appropriate constants and so is a good follow up to this post with a real world example.

Make sure you subscribe to my RSS feed (details below) if you haven’t already so you keep up to date with posts on my blog as they are made.