A class constant is a value that belongs to a class and never changes. It is defined with const and read with ::.
<?php
class Order
{
const STATUS_PENDING = "pending";
const STATUS_PAID = "paid";
const TAX_RATE = 0.18;
}
echo Order::STATUS_PAID . "\n";
echo Order::TAX_RATE;
paid
0.18
There is no $ and no new needed. Names are written in UPPER_CASE.
Why use them
Constants replace “magic values” scattered through your code. Compare:
if ($order->status === "paid") { ... } // a typo "piad" is silent
if ($order->status === Order::STATUS_PAID) { ... } // a typo is an error
Using them inside the class
<?php
class Cart
{
const MAX_ITEMS = 3;
private array $items = [];
public function add(string $item): bool
{
if (count($this->items) >= self::MAX_ITEMS) {
return false;
}
$this->items[] = $item;
return true;
}
}
$cart = new Cart();
foreach (["a", "b", "c", "d"] as $item) {
echo $cart->add($item) ? "added " : "full ";
}
added added added full
Visibility
Constants can be public, protected or private. Public is the default.
<?php
class Secrets
{
private const KEY = "internal";
public static function reveal(): string
{
return self::KEY;
}
}
echo Secrets::reveal() . "\n";
try {
echo Secrets::KEY;
} catch (Error $e) {
echo $e->getMessage();
}
internal
Cannot access private constant Secrets::KEY
Constants can use other constants
<?php
class Time
{
const MINUTE = 60;
const HOUR = self::MINUTE * 60;
const DAY = self::HOUR * 24;
}
echo Time::DAY;
86400
final constants (PHP 8.1+)
A final constant cannot be overridden in a child class.
<?php
class Base
{
final public const VERSION = "1.0";
}
Typed constants (PHP 8.3+)
From PHP 8.3 you can declare the type of a constant: const string STATUS_PAID = "paid";. On earlier versions this is a parse error.
<?php
class Order
{
public const string STATUS_PAID = "paid";
public const float TAX_RATE = 0.18;
}
static:: and inheritance
static::NAME looks the constant up in the class that was called, so a child class can change it.
<?php
class Shape
{
const SIDES = 0;
public function sides(): int
{
return static::SIDES;
}
}
class Triangle extends Shape
{
const SIDES = 3;
}
echo (new Triangle())->sides();
3
Constants vs enums
A group of related constants, such as order statuses, is often better as an enum (PHP 8.1+). An enum is its own type, so a function can accept only the allowed values. See Enums.
Reading all constants
<?php
class Color
{
const RED = "#f00";
const BLUE = "#00f";
}
print_r((new ReflectionClass("Color"))->getConstants());
Array
(
[RED] => #f00
[BLUE] => #00f
)