PHP - Class Constants
Class constants are useful if you need to define some constant data within a class.
A class constant has a fixed value, and cannot be changed once it is declared.
A class constant is declared inside a class with the const keyword.
The default visibility of class constants is public.
Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
PHP - Access Class Constants
A class constant can be accessed in two ways:
- A constant can be accessed from outside the class by using the class name followed by the scope resolution operator (
::) followed by the constant name:
Example
html
<?php
class
Goodbye {
const MESSAGE = "Thank you for visiting example.com!";
}
echo
Goodbye::MESSAGE; // Access constant
?>
- A constant can be accessed from inside the class by using the
selfkeyword followed by the scope resolution operator (::) followed by the constant name:
Example
html
<?php
class Goodbye {
const MESSAGE = "Thank you for visiting example.com!";
public function bye() {
echo self::MESSAGE; // Access
constant
}
}
$goodbye = new Goodbye();
$goodbye->bye();
?>