PHP - Class Constants
When a class needs some data that should never change, declare it as a class constant.
You create one inside the class with the const keyword. After that declaration, its value is fixed.
Unless you say otherwise, a class constant has public visibility.
Constant names are case-sensitive, and the usual recommendation is to write them entirely in uppercase.
PHP - Access Class Constants
There are two ways to reach a class constant.
1. From outside the class, write the class name, then the scope resolution operator (::), then the constant name:
Example
Here, code outside the class reads the constant through the class name:
Prompt
Create a PHP class Goodbye with a constant MESSAGE set to a greeting string. Access the constant from outside the class using the class name and scope resolution operator.
Output: PHP script
index.php
<?php
class Goodbye {
const MESSAGE = "Thank you for visiting PromptCookbook!";
}
echo Goodbye::MESSAGE; // Access constant
?>
Example
2. From inside the class, write the self keyword in place of the class name, then :: and the constant name:
Prompt
Create a PHP class Goodbye with a constant MESSAGE and a bye() method that accesses the constant from inside the class using self keyword.
Output: PHP script
index.php
<?php
class Goodbye {
const MESSAGE = "Thank you for visiting PromptCookbook!";
public function bye() {
echo self::MESSAGE; // Access constant
}
}
$goodbye = new Goodbye();
$goodbye->bye();
?>