Constants in PHP — const and define()
In this note, we will understand the difference in declaring PHP constants using the const keyword and the define() function.
Constants in PHP are "immutable" values that are specified only once and cannot be changed afterwards. When attempting to change the value, it will not change, and a PHP notice will appear: "Constant already defined":
define( 'FOO', 'val' ); define( 'FOO', 'val2' ); // Notice: Constant already defined echo FOO; //> val
Constants in PHP can be declared in two ways:
// 1 define( 'NAME', 'VALUE' ); // 2 const NAME = 'VALUE';
Each method has its own characteristics. To understand them, let's consider each step by step, and what changed with each PHP version.
How to create constants
PHP less than 5.3
Before 5.3 in PHP, constants could only be defined using define(). The const keyword appeared in version 5.3.
Constants can only store scalars. Scalar values are primitives: integer
, float
, string
, and boolean
. Types array
, object
, resource
, etc. are not scalars.
// scalars define( 'FOO', 10 ); define( 'FOO', 10.9 ); define( 'FOO', 'val' ); define( 'FOO', true ); // non-scalars define( 'FOO', array(1) ); // the constant will not be set, and we will get a Warning define( 'FOO', (object) array(1) ); // the constant will not be set, and we will get a Warning
Since PHP 5.3
The keyword const
appeared, and now a constant can also be defined using it.
However, in const
, you cannot specify an expression: variable, function, concatenation, and you must pass only a scalar:
const FOO = 'val'; // no errors const FOO = $var; // Parse error const FOO = home_url(); // Parse error const FOO = 5 + 10; // Parse error const FOO = 'foo'.'bar'; // Parse error
While for define()
, there are no such limitations.
define( 'FOO', 'val' ); // no errors define( 'FOO', $var ); // no errors define( 'FOO', home_url() ); // no errors define( 'FOO', 5 + 10 ); // no errors define( 'FOO', 'foo'.'bar' ); // no errors
PHP 5.6
It became possible to specify primitive PHP expressions in the values of const:
const FOO = 1 + 2; const FOO = 'foo' . 'bar';
It became possible to store arrays in constants:
const FOO = [1, 2, 3]; // works define( 'FOO', [1, 2, 3] ); // does not work in PHP 5.6, works in PHP 7.0
Difference between define() and const
#1 const
must be declared in the top scope
Because they are defined during script compilation. This means that const cannot be used inside functions/loops/expressions
or try/catch
blocks.
if ( 1 ) { const NAME = 'VALUE'; // does not work } // but if ( 1 ) { define('NAME', 'VALUE'); // works
#2 const is always case-sensitive
While define() allows creating case-insensitive constants:
define('NAME', 'VALUE', true); echo NAME; // VALUE echo name; // VALUE
#3 const only understands scalars, arrays, and expressions of primitives
You cannot pass variables, functions, expressions to const, but you can to define():
const FOO = $var; // Parse error const FOO = home_url(); // Parse error define('FOO', $var); // no errors define('FOO', home_url()); // no errors
Since PHP 5.6, const can also specify primitive expressions and arrays, not just scalars.
#4 const can store arrays from PHP 5.6, while define can from PHP 7.0
const FOO = [1, 2, 3]; // works in PHP 5.6 define('FOO', [1, 2, 3]); // works in PHP 7.0
#5 const depends on namespaces, while define does not
If we create a constant in a namespace, then:
- When using const, the constant will be in this namespace and will not be available outside of it.
- When using define, the constant is registered as global and will be available outside the namespace.
namespace My\Space; const FOO = 'bar'; define('FOOO', 'baz');
Now to refer to these constants outside the namespace, for example, from another file, you need to write like this:
echo \My\Space\FOO; // bar echo FOOO; // baz
Comparison summary
It is almost always better to define a constant using define(), because there are more possibilities and fewer chances to "catch" an error. Exceptions:
- If you have PHP version 5.6 and need to store an array in a constant, const will help.
- If you need the constant to not be in global visibility, but in namespace visibility.
PHP Class Constants
Declared only using const. The rules for them are as described above: they only accept scalars, do not understand PHP variables, functions, expressions.
The declared constant belongs to the class, it does not belong to any object, but is common to all objects (instances) of the class.
class My_Class { const NAME = 'VALUE'; // starting from PHP 5.6, you can use mathematical expressions const SEC_PER_DAY = 60 * 60 * 24; function print_name() { // accessing the class constant inside a method using self (the class itself) echo self::NAME; } } // accessing the constant outside the class // can be called from the global scope without instantiating a class instance echo My_Class::NAME;
Until PHP 7.1, class constants are always public - they do not have a private or protected status. However, starting from PHP 7.1, class constants can have a modifier:
class Foo { // Starting from PHP 7.1.0 public const BAR = 'bar'; private const BAZ = 'baz'; }
Class constants are somewhat similar to static class properties. Without going into details, the difference is that a constant cannot be changed.
class My_Class { const NAME = 'VALUE'; static $name = 'VALUE'; } echo My_Class::NAME; echo My_Class::$name;
"Magic" Constants
And finally, let's remember the special constants in PHP.
PHP has nine "magic" constants that change their value depending on the context in which they are used. For example, the value of __LINE__ depends on the line in the script where this constant is specified.
All "magic" constants are resolved during compilation, unlike regular constants, which are resolved during execution. Special constants are case-insensitive, and their list is given below:
Constant | Description |
---|---|
__LINE__ | Current line number in the file. |
__FILE__ | Full path and filename of the current file in which the constant is used. |
__DIR__ | PHP 5.3.0. Directory of the file in which the constant is used. Same as dirname(__FILE__). Does not have a trailing slash, except for the root directory. |
__FUNCTION__ | Function name. |
__CLASS__ | Class name. This name contains the namespace in which the class was declared (e.g., Foo\Bar). Also works in traits. When used in trait methods, it is the name of the class in which these methods are used. |
__TRAIT__ | PHP 5.4.0. Trait name. This name contains the namespace in which the trait was declared (e.g., Foo\Bar). |
__METHOD__ | Class method name. |
__NAMESPACE__ | PHP 5.3.0. Current namespace name. |
ClassName::class | PHP 5.5.0. Full class name (including namespace). |