Access Modifiers in PHP
Great! Let’s break down Access Modifiers in PHP — they're essential for controlling the visibility of classes, properties, and methods in Object-Oriented Programming.
? What Are Access Modifiers?
Access modifiers define how and where class properties or methods can be accessed.
PHP supports three access modifiers:
| Modifier | Access Level Description |
|---|---|
public | Accessible anywhere (inside and outside the class) |
protected | Accessible within the class and by inherited (child) classes |
private | Accessible only within the class itself |
? Examples
? public
class Car { public $brand = "Toyota"; public function showBrand() { echo $this->brand; }}$car = new Car();echo $car->brand; // ? Accessible outside the class? protected
class Vehicle { protected $speed = 100; protected function getSpeed() { return $this->speed; }}class Bike extends Vehicle { public function displaySpeed() { echo $this->getSpeed(); // ? Accessible in subclass }}$bike = new Bike();$bike->displaySpeed(); // ? Works// echo $bike->speed; // ? Error: Cannot access protected property? private
class Person { private $name = "Alice"; private function getName() { return $this->name; } public function showName() { return $this->getName(); // ? OK within the same class }}$person = new Person();echo $person->showName(); // ? Outputs: Alice// echo $person->name; // ? Error: Cannot access private property? Summary
| Visibility | Same Class | Subclass | Outside Class |
|---|---|---|---|
public | ? | ? | ? |
protected | ? | ? | ? |
private | ? | ? | ? |