PHP Constants

Constants are used to define values that remain unchanged throughout the execution of a program. They are useful for defining configuration values, predefined values, or other data that should not be modified during runtime.

When it comes to Object-Oriented Programming (OOP) in PHP, you can define constants within classes. Here’s an example of how to work with constants in PHP OOP:

class MyClass {
    const MY_CONSTANT = 10;

    public function printConstant() {
        echo self::MY_CONSTANT;
    }
}

In the example above, we define a class called MyClass and declare a constant MY_CONSTANT using the const keyword. The constant value is set to 10. The self:: keyword is used to access the class constant from within the class itself.

To use the constant outside the class, you can refer to it using the class name:

echo MyClass::MY_CONSTANT;

You can also access the constant within class methods:

$object = new MyClass();
$object->printConstant();  // Outputs: 10

It’s important to note that class constants are implicitly public, so they can be accessed from anywhere.

Furthermore, unlike properties, you cannot override or modify the value of a constant once it has been defined. Constants are static, meaning they belong to the class itself and not to any specific object instance. Therefore, they are accessed using the class name instead of object instances.

Using constants in PHP OOP can provide a convenient way to define values that remain consistent across the class and its instances, without the risk of accidental modification.