Constants in PHP are used to store a value and they cannot be changed or undefined afterwards during the execution of the script.
<?php define('FOO', 'value');
Constant name start with a letter or underscore followed by any alfanumeric characters A-Z, a-z.
Scope of the constants is global. They can be used anywhere in your PHP script.
There are two ways to define constants in PHP:
const BAR = 'value'
Each way has some benefits and drawbacks.
define()is a function
define()defines constants at run time
constis a language construct
constdefines constants at compile time
constinside functions, loops, if statements or try/catch blocks
<?php const FOO = 'Hello'; // Outputs "Hello" echo FOO; const BAR = FOO.' world';
Constants can be also arrays:
<?php const PLANETS = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']; // Outputs "Earth" echo PLANETS;
Constants can be also defined as expressions:
<?php const FOO = 2 * 3; // Outputs 6 echo FOO; define('BAR', 3 * 4); // Outputs 12 echo BAR;
Magic constants are special constants that are provided by PHP and have value depending where they are used.
Constants in PHP are resolved at runtime (when the script is parsed by PHP). Magical constants are resolved at compile time.
All magic constants are described below:
||The current file line number.|
||The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.|
||The directory of the file without a trailing slash (unless it is the root directory). When used inside an include, the directory of the included file is returned. Equivalent to
||The function name.|
||The class name with the namespace it was declared in (e.g. Foo\Bar). When used in a trait method, it is the name of the class the trait is used in.|
||The trait name with the namespace it was declared in (e.g. Foo\Bar).|
||The class method name.|
||The name of the current namespace.|
||The fully qualified class name.|