In PHP OOP, class constants are similar to class properties, but they are immutable and their values cannot be changed once they are defined. Class constants are defined using the const keyword and are accessed using the :: operator.
Here’s an example of a class with a constant:
class Circle {
const PI = 3.14;
public $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return self::PI * pow($this->radius, 2);
}
}
$circle = new Circle(5);
echo Circle::PI; // Output: 3.14
echo $circle->area(); // Output: 78.5
In this example, the Circle
class has a constant named PI
that is set to the value 3.14
. The class also has a property named $radius
and a method named area()
that calculates the area of a circle using the formula pi * radius^2
. The area()
method uses the self::PI
syntax to access the value of the PI
constant.
To access the value of the constant, we use the ::
operator:
echo Circle::PI; // Output: 3.14
We can also use the constant in a class method, as shown in the area()
method of the Circle
class.
In summary, class constants in PHP OOP are immutable values that are defined using the const
keyword. They are accessed using the ::
operator and can be used in class methods.