What are Class constants:
In PHP, class constants are similar to regular constants but are associated with a specific class. They provide a way to define values that remain constant and do not change throughout the execution of the script. Class constants are accessed using the scope resolution operator :: and are defined using the const keyword.
Declaration of Class Constants:
Class constants are declared within the class using the const keyword followed by the constant name and its value. They must have a visibility modifier (public, protected, or private), and their values must be scalar values (integers, floats, strings, or booleans) or arrays.
<?php
class MyClass {
const PI = 3.14;
public const APP_NAME = "MyApp";
private const MAX_ATTEMPTS = 3;
}
?>
Accessing Class Constants:
Class constants are accessed using the scope resolution operator :: followed by the constant name.
<?php
echo MyClass::PI; // Output: 3.14
echo MyClass::APP_NAME; // Output: MyApp
?>
Visibility of Class Constants:
Class constants can have different visibility modifiers:
public: Accessible from anywhere, both inside and outside the class.
protected: Accessible from within the class and its subclasses (child classes).
private: Accessible only from within the class itself.
Example:
<?php
class Math {
public const PI = 3.14;
protected const EULER = 2.718;
private const GOLDEN_RATIO = 1.618;
}
echo Math::PI; // Output: 3.14
// echo Math::EULER; // This will cause a fatal error because EULER is protected
// echo Math::GOLDEN_RATIO; // This will cause a fatal error because GOLDEN_RATIO is private
Use Cases:
Class constants are useful for defining values that remain constant across instances of a class.
They provide a way to define meaningful names for magic numbers or strings used in the class.
Important Points:
Class constants are associated with the class itself, not with instances of the class.
They provide a way to define global constants within the context of a class.
Class constants are immutable and cannot be modified or redefined after they are declared.
Class constants offer a convenient and organized way to define and access constants within the scope of a class, enhancing code readability and maintainability.