Constants can be defined using the const keyword, or by using the define() function. While define() allows a constant to be defined to an arbitrary expression, the const keyword has restrictions.
Constants have a global scope by default. It's recommended to use uppercase names for constants.
define()
define("PI", 3.14159); define("APP_NAME", "My Application");
You can define constants dynamically (using a variable as the name):
$name = "VERSION"; define($name, "1.0.0"); echo VERSION; // 1.0.0
Works only in the global scope (not inside classes).
const keyword
const PI = 3.14159; const APP_NAME = "My Application";
Constants are defined at compile-time (not runtime).
You cannot use dynamic names:
$name = "VERSION"; const $name = "1.0.0"; // Parse error
Can be used inside classes and interfaces:
class Config { const VERSION = "1.0.0"; const DEBUG = true; } echo Config::VERSION; // 1.0.0
Differences: define() vs const
When defined:
Scope:
Dynamic names:
Performance:
Magic Constants
There are a few magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in a script. All these "magical" constants are resolved at compile time, unlike regular constants, which are resolved at runtime. These special constants are case-insensitive and are as follows:
Source: Orkhan Alishov's notes