PHP Class Constant
A PHP class constant is a fixed value that remains the same throughout the lifetime of a class. Constants are defined using the const keyword and are typically used to define immutable values that are shared across all instances of a class. Constants are accessed using the scope resolution operator ::.
Here’s a basic example to illustrate PHP class constants:
Example 1: Defining and Accessing Class Constants
<?php
class MyClass {
const MY_CONSTANT = 'Hello, World!';
public function showConstant() {
echo self::MY_CONSTANT;
}
}
// Accessing the constant from outside the class
echo MyClass::MY_CONSTANT; // Output: Hello, World!
// Accessing the constant from inside the class
$obj = new MyClass();
$obj->showConstant(); // Output: Hello, World!
?>
In this example:
MY_CONSTANT is defined within MyClass.
- The constant is accessed from outside the class using
MyClass::MY_CONSTANT.
- The constant is accessed from inside the class using
self::MY_CONSTANT.
Example 2: Constants in Inheritance
When a class is extended, the child class can access the constants of the parent class.
<?php
class ParentClass {
const PARENT_CONSTANT = 'Parent Constant';
}
class ChildClass extends ParentClass {
const CHILD_CONSTANT = 'Child Constant';
public function showConstants() {
echo self::CHILD_CONSTANT . "\n";
echo parent::PARENT_CONSTANT . "\n";
}
}
// Accessing the constants from outside the class
echo ChildClass::CHILD_CONSTANT; // Output: Child Constant
echo ChildClass::PARENT_CONSTANT; // Output: Parent Constant
// Accessing the constants from inside the class
$child = new ChildClass();
$child->showConstants();
// Output:
// Child Constant
// Parent Constant
?>
In this example:
ParentClass has a constant PARENT_CONSTANT.
ChildClass extends ParentClass and adds its own constant CHILD_CONSTANT.
- The child class can access its own constants using
self::CONSTANT_NAME and parent class constants using parent::CONSTANT_NAME.
Example 3: Using Constants in Static Methods
Constants can also be used in static methods within the class.
<?php
class MyClass {
const MY_CONSTANT = 'Static Constant';
public static function showStaticConstant() {
echo self::MY_CONSTANT;
}
}
// Accessing the static method from outside the class
MyClass::showStaticConstant(); // Output: Static Constant
?>
In this example:
MY_CONSTANT is accessed within the static method showStaticConstant using self::MY_CONSTANT.
- The static method
showStaticConstant is called using MyClass::showStaticConstant.
These examples demonstrate how to define and use class constants in PHP, including accessing them from within the class, from outside the class, in child classes, and in static methods.