Class constants are useful for defining fixed values within a class.
A class constant is declared inside a class using the const
keyword.
Once declared, a constant’s value cannot be changed.
Class constants are case-sensitive, but it is recommended to use uppercase letters for naming them.
You can access a constant from outside the class using the class name, the scope resolution operator (::
), and the constant name, as shown here:
<?php class Goodbye { const LEAVING_MESSAGE = “Thank you for visiting W3Schools.com!”; } echo Goodbye::LEAVING_MESSAGE; ?> |
Alternatively, you can access a constant from within the class using the self
keyword, followed by the scope resolution operator (::
) and the constant name, as shown here:
<?php class Goodbye { const LEAVING_MESSAGE = “Thank you for visiting W3Schools.com!”; public function byebye() { echo self::LEAVING_MESSAGE; } } $goodbye = new Goodbye(); $goodbye->byebye(); ?> |