PHPOOP - Class Constants
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 theconst keyword.
The default visibility of class constants ispublic.
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:
1. A constant can be accessedfom outside the class by using the class name followed by the scope resolution operator (::) followed by the constant name:
Example
class Goodbye {
const MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo Goodbye::MESSAGE; // Access constant
?>
2. A constant can be accessedfom inside the class by using theself keyword followed by the scope resolution operator (::) followed by the constant name:
Example
class Goodbye {
const MESSAGE = "Thank you for visiting W3Schools.com!";
public function bye() {
echo self::MESSAGE; // Access constant
}
}
$goodbye = new Goodbye();
$goodbye->bye();
?>

