In this tutorial, we will learn about how to declare Constants in PHP class and fetch them using class objects. A constant is something like a variable used to store some value excepted the value of constants cannot be changed once it is declared. We can declare constants in PHP class using the const keyword. Please keep in your mind that constant identifiers are case-sensitive.
Page Contents
It is recommeded to write every constant name in upper case for example: MIN_AGE =10
How to define constants in PHP class:
<?php
class Rules {
const MIN_AGE = "Minimum age to cast vote is 18";
}
echo Rules::MIN_AGE;
?>
As in the above example program you can see we used the const keyword to define a constant inside class and after that, we used the class name::(scope resolution operator) followed by the constant name to fetch the value of constant.
How to access the value of constant inside a class:
<?php
class Rules {
const MIN_AGE = "Minimum age to cast vote is 18";
function showAgeMessage(){
echo self::MIN_AGE;
}
}
$rules =new Rules;
$rules->showAgeMessage();
?>
As in the above example, you can see we used the self keyword to access the value of the constant inside the class.