PHP OOP - 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 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:
1. A constant can be accessed fom outside the class by using the class name
followed by the scope resolution operator (::) followed by the constant
name:
Example
<?php
class
Goodbye {
const MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo
Goodbye::MESSAGE; // Access constant
?>
Try it Yourself »
2. A constant can be accessed fom inside the class by using the
self keyword followed by the scope resolution operator (::) followed by the constant name:
Example
<?php
class Goodbye {
const MESSAGE = "Thank you for visiting W3Schools.com!";
public function bye() {
echo self::MESSAGE; // Access
constant
}
}
$goodbye = new Goodbye();
$goodbye->bye();
?>
Try it Yourself »