What are PHP OOP class constants?
Overview
The word constant emphasizes that something is unchangeable. Class constants can be helpful to declare some constant data within a class. Using the const keyword enables us to communicate a constant in a class.
A constant can be accessed outside the class by writing the class name, the scope resolution operator:: and then the constant's name.
Example
<?phpclass Description {const DESCRIPTION_MESSAGE = "Study PHP Class Constants from Educative!";}echo Description::DESCRIPTION_MESSAGE;?>
Explanation
- Lines 2–5: We declare a class named
Descriptionand a constant namedDESCRIPTION_MESSAGEwhich holds a specific message. - Line 7: We print the constant by accessing it from outside the class
Description.
We can access a constant within a class through the self keyword, which is followed by the scope resolution operator ::, and then the constant name.
Example
<?phpclass Description {const DESCRIPTON_MESSAGE = "Thank you for visiting W3Schools.com!";public function CallInsideClass() {echo self::DESCRIPTON_MESSAGE;}}$d1 = new Description();$d1->CallInsideClass();?>
Explanation
- Lines 2–3: We declare a class named
Descriptionand a constant namedDESCRIPTION_MESSAGEwhich holds a specific message. - Lines 4–5: We call a public function
CallInsideClass(). This function prints the class constant. As it is a public function, we can call it from outside the class. - Lines 9–10: We create a new class
object. This object then calls the public class functionCallInsideClass().