What are Constants?
Constants are values that never change. In PHP OOP, a class constant is a value that is associated with a class.
- They are declared using the const keyword within a class.
- You access class constants using the class name followed by ::
Why use them? Class constants are useful for storing values that are related to the class and won't change during the script's execution. They're like predefined values that belong to the class.
Example:
class MathOperations {
const PI = 3.14159;
const EULER_NUMBER = 2.71828;
}
Here, PI and EULER_NUMBER are class constants.
Now, we can use these constants without creating an instance of the class:
echo MathOperations::PI; // Outputs: 3.14159
echo MathOperations::EULER_NUMBER; // Outputs: 2.71828
These constants are like special values that belong to the MathOperations class, and we can use them in our calculations or wherever needed. They won't change while the script is running, making them constant throughout the class.