PHP - Using Class Constants

In PHP, class constants are values that remain constant and cannot be changed once they are defined within a class. These constants are accessed using the scope resolution operator (::). Here's how you can use class constants in advanced PHP:

class Math {

    const PI = 3.14159;

    const EULER_NUMBER = 2.71828;

}
echo Math::PI;  // Output: 3.14159
echo Math::EULER_NUMBER;  // Output: 2.71828

In the example above, PI and EULER_NUMBER are class constants defined within the Math class. You can access these constants using the class name followed by the scope resolution operator (::).

Class constants are useful for defining values that don't change throughout the execution of the script and are associated with the class. They can be used for configuration values, mathematical constants, error codes, and more.

Key points to remember when using class constants:

Accessing Constants: Use the scope resolution operator ClassName::CONSTANT_NAME to access class constants from outside the class.

Visibility: Class constants are implicitly public and can be accessed from outside the class. They don't require access modifiers like properties or methods.

Value Assignment: Class constants' values cannot change after they are defined. They are constant throughout the script's execution.

Naming Convention: By convention, class constants are often written in uppercase with underscores as word separators (e.g., MY_CONSTANT).

Namespacing: If the class is within a namespace, you need to use the fully qualified class name to access the constant (e.g., Namespace\ClassName::CONSTANT_NAME).

Inheritance: Class constants are inherited by child classes. If a child class defines a constant with the same name, it will override the parent class constant only in that child class.

Here's an example illustrating inheritance of class constants:

class ParentClass {

    const CONSTANT_A = "Value A";

}

class ChildClass extends ParentClass {

    const CONSTANT_B = "Value B";

}
echo ParentClass::CONSTANT_A;  // Output: Value A
echo ChildClass::CONSTANT_A;   // Output: Value A
echo ChildClass::CONSTANT_B;   // Output: Value B

Class constants provide a way to create meaningful names for fixed values in your classes, making your code more readable and maintainable.