const
As a PHP developer, you may have used constants to define values that remain unchanged throughout your code. The "const" keyword is a fundamental building block
The PHP const Keyword
A constant is a named value that cannot change while a script runs. The const keyword is one of two ways PHP lets you declare a constant (the other is the define() function). Unlike a variable, a constant has no leading $, and once it is set you cannot reassign or unset() it.
This guide covers what const does, how it differs from define(), where you are allowed to use it, and the common pitfalls that trip people up.
Syntax
You can use const at the top level of a script (a global constant) or inside a class, interface, or trait (a class constant):
const NAME = value; // global constantclass ClassName {
const NAME = value; // class constant, accessed as ClassName::NAME
}By convention constant names are written in UPPER_SNAKE_CASE. A name must start with a letter or underscore and contain only letters, digits, and underscores.
const vs define()
PHP gives you two tools that look similar but behave differently. Knowing the trade-offs saves debugging time:
| Feature | const | define() |
|---|---|---|
| Evaluated | At compile time | At run time |
Can run conditionally (inside if) | No | Yes |
| Works inside a class | Yes (class constant) | No |
| Name from a variable/expression | No | Yes (define($name, ...)) |
| Value | Constant expressions only | Any expression |
Rule of thumb: reach for const for fixed, always-defined values (especially class constants), and define() when the name or value is decided while the program runs.
<?php
// define() can be conditional; const cannot.
if (!defined('ENVIRONMENT')) {
define('ENVIRONMENT', 'production');
}
// This would be a fatal parse error — const cannot live inside an if-block:
// if (true) { const FOO = 1; }See the dedicated define() chapter and the PHP constants overview for more.
Examples
Class constant and global constant
<?php
// Example 1 — a class constant referenced with self::
class Circle
{
const PI = 3.14;
public $radius;
public function __construct($radius)
{
$this->radius = $radius;
}
public function getArea()
{
return self::PI * $this->radius * $this->radius;
}
}
$myCircle = new Circle(5);
echo "Area of circle: " . $myCircle->getArea() . PHP_EOL;
// Output: Area of circle: 78.5
// Example 2 — a global constant
const MY_NAME = "John";
echo "My name is " . MY_NAME;
// Output: My name is JohnYou read a class constant with the :: (scope resolution) operator — self::PI from inside the class, Circle::PI from outside. A global constant is used by name with no $. For more on classes, see PHP classes and objects and the class constants chapter.
Constant expressions and arrays
A const value must be a constant expression — something PHP can evaluate without running any code. You may use literals, operators, and other already-defined constants, and (since PHP 5.6) the result can be an array.
<?php
const SECONDS_PER_MINUTE = 60;
const SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60; // built from another const
const ALLOWED_ROLES = ['admin', 'editor', 'viewer'];
echo SECONDS_PER_HOUR . PHP_EOL; // 3600
echo ALLOWED_ROLES[1] . PHP_EOL; // editorFunction calls and object instances are not allowed in a const value because they cannot be resolved at compile time.
Class constants: visibility, interfaces, and final
Class constants belong to the class, not to any single object, so you do not need an instance to read them. Since PHP 7.1 you can also give them a visibility modifier:
<?php
interface HasStatus
{
// Interface constants are always public.
const DEFAULT_STATUS = 'pending';
}
class Order implements HasStatus
{
public const TAX_RATE = 0.2; // readable everywhere
protected const MAX_QTY = 99; // this class + subclasses
private const SECRET = 'x'; // this class only
public function status(): string
{
return self::DEFAULT_STATUS; // inherited from the interface
}
}
echo Order::TAX_RATE . PHP_EOL; // 0.2
echo (new Order())->status() . PHP_EOL; // pendingInterfaces can declare constants too (always public) — see PHP interfaces. A class constant can be marked final (PHP 8.1+) to stop subclasses from overriding it.
Common gotchas
- No
$on a constant.echo MY_NAME;works;echo $MY_NAME;looks for a variable and fails. - Cannot be changed or unset. Reassigning a constant is a fatal error;
unset()does not work on constants. - Compile-time only. You cannot wrap
constin anif, loop, or function based on runtime data — usedefine()for that. - Constants are global in scope. A global
constis visible inside functions withoutglobal, unlike a normal variable.
Benefits
- Readability: a named constant such as
TAX_RATEdocuments intent far better than a magic number. - Maintainability: change a value in one place instead of hunting for every literal.
- Safety: the value is read-only, so it cannot be overwritten by accident anywhere in the codebase.
Conclusion
The const keyword defines compile-time constants — both global and inside classes — that stay fixed for the life of a script. Use it for fixed values you always know up front, prefer class constants for values that belong to a type, and switch to define() when you need a constant created conditionally or with a dynamic name. To go deeper, continue with the PHP constants and class constants chapters.