Fix – PHP Notice: Use of undefined constant.

This is a common PHP notice/warning that occurs whenever you attempt to use an undefined constant. In case you didn’t already know, a constant is a simple value that cannot change during the execution of a script.

In other words, if you set constant A to “123”, then you will not be able to change it to “456” at a later stage.

Here is an example of a constant being defined in PHP.

//create a constant called PI
define('PI', 3.14);

//print it out to the screen.
echo PI;

PI is a good example of a constant because the value of PI never changes. It will always be 3.14 and nothing in our code should be able to change that.

In some cases, this kind of notice can appear even if you aren’t using any constants.

Forgetting to use a $ symbol at the start of a variable name.

Take the following example.

//Create a simple variable called $name.
$name = "Wayne";

//Print it out.
echo name;

In the above example, we forgot to place a dollar sign ($) in front of the $name variable. This will result in the following error.

Notice: Use of undefined constant name – assumed ‘name’

Because there is no dollar sign in front of the variable “name”, PHP will assume that we are trying to reference a constant variable called “name”.

Forgetting to place quotes around strings.

This issue can also occur if you incorrectly reference an array key or index.

//Print POST variable called "email".
echo $_POST[email];

In the example above, we didn’t place quotes around the $_POST variable “email”. This will cause the following notice:

Notice: Use of undefined constant name – assumed ’email’

To fix this, we’d obviously have to do the following.

//Print POST variable called "email".
echo $_POST["email"];

As you can see, the fix here was to place quotes around the string “email”.

Here is an example of an associated array that will cause this error:

//A custom array
$myArray = array(
    title => 'This is a title',
    page => 'page-url'
);

In this case, I have quoted the array’s elements. However, I have failed to quote the array’s keys.

As a result, our PHP script will spit out warnings about title and page being undefined constants.

A basic gist is this: If it’s not a constant, then it must be accompanied by a dollar sign ($) or quotes.