PHP Class Constants
In this page:
What Is a Class Constant?
A class constant is a named value defined with const directly inside a class body, shared by every instance and impossible to change after definition. Unlike instance properties, a constant has no $ sigil and doesn't belong to any one object -- it belongs to the class itself, so its value is identical everywhere the class is used.
Example: What Is a Class Constant?
<?php
class Circle {
const PI = 3.14159;
}
echo Circle::PI;
?>
Login to try C/C++/Java/PHP code in the editor
Accessing Class Constants
You read a class constant with the scope resolution operator: ClassName::CONST_NAME from outside the class, or self::CONST_NAME from within its own methods. Because constants aren't tied to an instance, you never need $this-> or an object variable to reach them.
Example: Accessing Class Constants
<?php
class Circle {
const PI = 3.14159;
function area($r) {
return self::PI * $r * $r;
}
}
$c = new Circle();
echo $c->area(2) . "\n";
echo Circle::PI;
?>
Login to try C/C++/Java/PHP code in the editor
Constants vs Instance Properties
An instance property (private $rate) can hold a different value per object and can be reassigned; a class constant is fixed at definition time and shared identically across every instance. Use a constant for a value that's inherently part of the class's definition -- like a fixed tax rate or a status code -- not something that varies per object.
Example: Constants vs Instance Properties
<?php
class Invoice {
const TAX_RATE = 0.08;
private $amount;
function __construct($amount) {
$this->amount = $amount;
}
}
echo Invoice::TAX_RATE;
?>
Login to try C/C++/Java/PHP code in the editor
Visibility on Constants
Since PHP 7.1, class constants can have visibility modifiers just like properties and methods: public const, protected const, or private const. A private const is only reachable from inside the declaring class itself, letting you hide internal implementation constants from outside code.
Example: Visibility on Constants
<?php
class Config {
public const VERSION = "1.0";
private const SECRET_KEY = "abc123";
function getKey() {
return self::SECRET_KEY;
}
}
echo Config::VERSION . "\n";
echo (new Config())->getKey();
?>
Login to try C/C++/Java/PHP code in the editor
Constants and Enums
PHP 8.1 introduced true enum types as a more structured alternative for a fixed set of related named values, with type-safety class constants don't have. Class constants remain the right tool for a single fixed value (like a version string or a limit), while an enum fits better when you have several named, mutually-exclusive cases.
Example: Constants and Enums
<?php
class Status {
const ACTIVE = 'active';
const INACTIVE = 'inactive';
}
echo Status::ACTIVE;
// PHP 8.1 enums are a more structured alternative for fixed named cases
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: