PHP OOP - Class Constants
In PHP Object-Oriented Programming (OOP), class constants are similar to regular constants, but they are defined within a class and are accessed using the scope resolution operator (::). Class constants provide a way to define values that remain constant throughout the execution of the script and are associated with a specific class.
Example
class MyClass { // Define a class constant const MY_CONSTANT = "Hello, world!"; // Method to access the class constant public function getConstant() { return self::MY_CONSTANT; // Accessing class constant using self keyword } } // Accessing the class constant from outside the class echo MyClass::MY_CONSTANT . "\n"; // Creating an object of the class to access the constant through a method $obj = new MyClass(); echo $obj->getConstant() . "\n";You can click on above box to edit the code and run again.
Output
In this example:
- MY_CONSTANT is a class constant defined within the MyClass class using the const keyword.
- It's accessed using the scope resolution operator (::) outside the class.
- Inside the class, it's accessed using the self keyword followed by the scope resolution operator (::).
- Class constants are accessed without the use of the dollar sign ($).
- They are useful for defining values that should not change throughout the execution of the script, such as configuration settings or fixed values.
- Class constants are case-sensitive by default and can be accessed from both static and non-static contexts.