Class constants are fixed values defined using the const
keyword inside a class. They are accessed using ClassName::CONSTANT
and do not require an object. Constants cannot be changed once defined. Inside the class, use self::CONSTANT
or parent::CONSTANT
if inherited. They are ideal for configuration values or fixed settings.
1. Basic Example of Class Constant
class AppConfig {
const SITE_NAME = "MyWebsite";
}
echo AppConfig::SITE_NAME; // Output: MyWebsite
File: class_constant.php
2. Using Class Constants Inside Methods
class Math {
const PI = 3.14159;
public function showPi() {
return self::PI; // use self:: inside class
}
}
$obj = new Math();
echo $obj->showPi(); // Output: 3.14159
File: constant_inside_class.php
3. Accessing Parent Class Constant in Child
class ParentClass {
const MESSAGE = "Hello from parent";
}
class ChildClass extends ParentClass {
public function showMsg() {
return parent::MESSAGE;
}
}
$child = new ChildClass();
echo $child->showMsg(); // Output: Hello from parent
File: constant_inheritance.php
4. Constants vs Variables
Feature | Constant (const ) |
Variable ($var ) |
---|---|---|
Can change? | ❌ No | ✅ Yes |
Access | ClassName::CONSTANT |
$object->property |
Defined using | const |
public/private |
Needs object? | ❌ No | ✅ Yes |