A constant is a fixed value that remains unchanged during the execution of a program. Once defined in PHP, a constant cannot be modified. Constants are typically defined using the define() function. The naming rules for constants are similar to variables, but unlike variables, constants cannot have their values changed after definition.
When defining constants with names starting with a number, PHP will generate an error. This is because PHP interprets a constant name starting with a digit as a numeric literal, causing syntax issues. For example:
define('3L', 'three');
PHP internally tries to parse this as:
define(3L, 'three');
Since numeric literals are not valid constant names, this leads to a syntax error.
A simple way to avoid the problem is to prepend a letter before the numeric part of the constant name, like this:
// Example of adding a letter before the constant name
define('L3', 'three');
echo L3; // Outputs 'three'
This ensures PHP recognizes the constant name as L3 instead of starting with a digit.
Another standard practice is to use string literal constant names explicitly wrapped in quotes, for example:
// Example of using string constant names
define('THREE', 'three');
echo THREE; // Outputs 'three'
This clearly defines the constant name as a string and avoids parsing ambiguity.
PHP also supports escaping numeric constant names using a backslash. For example:
// Example of escaping numeric constant names
define('\3L', 'three');
echo L3; // Outputs 'three'
This method can prevent errors caused by illegal numeric constant names, though it is less commonly used.
When encountering PHP errors about illegal numeric constant names, you can resolve them using any of the three methods above. The most common and recommended approaches are to add a letter before the constant name or use string literal constant names. Following proper naming conventions not only avoids syntax errors but also enhances code readability and maintainability while reducing the presence of “magic numbers” in your code.