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.
<?php class Description { const DESCRIPTION_MESSAGE = "Study PHP Class Constants from Educative!"; } echo Description::DESCRIPTION_MESSAGE; ?>
Description
and a constant named DESCRIPTION_MESSAGE
which holds a specific message. 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.
<?php class Description { const DESCRIPTON_MESSAGE = "Thank you for visiting W3Schools.com!"; public function CallInsideClass() { echo self::DESCRIPTON_MESSAGE; } } $d1 = new Description(); $d1->CallInsideClass(); ?>
Description
and a constant named DESCRIPTION_MESSAGE
which holds a specific message.CallInsideClass()
. This function prints the class constant. As it is a public function, we can call it from outside the class.object
. This object then calls the public class function CallInsideClass()
.
RELATED TAGS
CONTRIBUTOR
View all Courses