PHP Access Modifiers (public, private, protected)
In PHP Object-Oriented programming, public, private, and protected are access modifiers (visibility keywords) used to control how properties (variables) and methods (functions) of a class can be accessed.
They are important in Object-Oriented Programming (OOP) because they enforce encapsulation (controlling how data is exposed and used).
Public
Members declared public can be accessed from inside the class, outside of the class and by subclasses (child classes). If no visibility is specified on a property the default will be public.
class Car {
public $brand;
public function setBrand($brand) {
$this->brand = $brand; // accessible inside the class
}
}
$car = new Car();
$car->brand = "Toyota"; // accessible outside the class
echo $car->brand; // Output: Toyota
Private
Members declared private can only be accessed inside of the class that defines them. They cannot be accessed from outside the class or by subclasses.
class Car {
private $engineNumber;
public function setEngineNumber($num) {
$this->engineNumber = $num; // accessible inside the class
}
public function getEngineNumber() {
return $this->engineNumber; // allowed via public method
}
}
$car = new Car();
$car->setEngineNumber("ENG123");
// echo $car->engineNumber; ERROR: Cannot access private property
echo $car->getEngineNumber(); // Output: ENG123
Protected
Members declared protected can be accessed inside of the class, in child(sub) classes that inherit from it. They cannot be accessed directly from outside of the class… only subclasses.
class Vehicle {
protected $type = "Generic Vehicle";
protected function getType() {
return $this->type;
}
}
class Car extends Vehicle {
public function showType() {
return $this->getType(); // accessible in child class
}
}
$car = new Car();
// echo $car->type; ERROR: Cannot access protected property
echo $car->showType(); // Output: Generic Vehicle