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.
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
