In PHP, class constants are similar to regular constants but are defined within a class. Class constants are accessed using the `::` scope resolution operator and are useful for defining values that should not change throughout the execution of a script. They are declared using the `const` keyword inside a class and are accessed without using the `$` prefix.
class ClassName {
const CONSTANT_NAME = value;
}
Example of Class Constants:
Here's an example to illustrate how class constants work in PHP:
class Math {
const PI = 3.14159;
const EULER = 2.71828;
public static function areaOfCircle($radius) {
return self::PI * $radius * $radius;
}
}
// Accessing class constants
echo "Value of PI: " . Math::PI . "<br>"; // Output: Value of PI: 3.14159
echo "Value of EULER: " . Math::EULER . "<br>"; // Output: Value of EULER: 2.71828
// Using a class constant in a method
$radius = 5;
$area = Math::areaOfCircle($radius);
echo "Area of circle with radius {$radius}: {$area}<br>"; // Output: Area of circle with radius 5: 78.53975
In this example:
Class constants can have different visibility levels:
Example with Different Visibility:
class MyClass {
public const PUBLIC_CONST = "Public Constant";
protected const PROTECTED_CONST = "Protected Constant";
private const PRIVATE_CONST = "Private Constant";
public function displayConstants() {
echo self::PUBLIC_CONST . "<br>"; // Accessible within the class
echo self::PROTECTED_CONST . "<br>"; // Accessible within the class
echo self::PRIVATE_CONST . "<br>"; // Accessible within the class
}
}
// Accessing class constants
echo MyClass::PUBLIC_CONST . "<br>"; // Output: Public Constant
// echo MyClass::PROTECTED_CONST . "<br>"; // Error: Cannot access protected constant
// echo MyClass::PRIVATE_CONST . "<br>"; // Error: Cannot access private constant
$obj = new MyClass();
$obj->displayConstants(); // Output: Public Constant, Protected Constant, Private Constant
In this example:
Class constants in PHP are defined using the const keyword within a class and provide a way to define values that do not change during script execution. They are accessed using the :: scope resolution operator and are useful for defining values that are associated with a class. Class constants can have different visibility levels and are a useful tool in object-oriented PHP programming for defining and using constants within a class.