Modifier¶
A modifier is a keyword that changes the behavior or properties of a class element, such as property, method, or constant. PHP supports several categories of modifiers:
Visibility modifiers control access to class members:
public: accessible from anywhere, by defaultprotected: accessible within the class and its subclassesprivate: accessible only within the declaring class
Other modifiers:
static: belongs to the class itself rather than instancesabstract: declares a class or method that must be implemented by subclassesfinal: prevents a class from being extended or a method from being overriddenreadonly: makes a property immutable after initializationreadonly class: makes all properties readonly
Modifiers are essential for implementing encapsulation, polymorphism, and other OOP principles. They enforce design constraints at the language level, improving code safety and clarity.
<?php
abstract class Shape {
protected float $area;
abstract public function calculate(): float;
final public function describe(): string {
return 'This shape has an area of ' . $this->calculate();
}
}
class Circle extends Shape {
public function __construct(
private readonly float $radius
) {}
public function calculate(): float {
return pi() * $this->radius 2;
}
}
$c = new Circle(5);
echo $c->describe();
?>
See also PHP Visibility and PHP Class Keywords.
Related : Visibility, Private Visibility, Protected Visibility, Public Visibility, static, Abstract Keyword, Final Keyword, Readonly, Data Hiding, Encapsulation, OOP (Object Oriented Programming), Properties, Method, Static Constant