PHP Constants
Constants hold a value that cannot change once defined.
Syntax
define("NAME", value);
const NAME = value;A constant is like a variable, except its value can never be changed after it is set. You do not use the $ sign with constants.
Two ways to define
- The
define()function. - The
constkeyword.
By convention constant names are written in UPPERCASE.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- App-wide settings that must never change at runtime β site name, version.
- Fixed limits and magic numbers such as MAX_UPLOAD or TAX_RATE.
- Environment flags read in many places, e.g. IS_PRODUCTION.
More examples
define() vs const
define() runs at runtime; const is evaluated at compile time and must sit at the top level.
<?php
define("SITE_NAME", "SoundsCode");
const VERSION = "2.1";
echo SITE_NAME . " v" . VERSION;Constants inside a class
Class constants belong to the class and are read with self::PI or Circle::PI.
<?php
class Circle {
const PI = 3.14159;
public function area($r) {
return self::PI * $r * $r;
}
}
echo (new Circle)->area(2);Guard with defined()
defined() checks whether a constant exists before you use or redefine it.
<?php
if (!defined("MODE")) {
define("MODE", "live");
}
echo defined("MODE") ? MODE : "unset";
Discussion