PHP OOP - Access Modifiers

In PHP (and other object-oriented programming languages), access modifiers control the visibility of class properties and methods. PHP supports three main access modifiers:

1. Public

  • Accessible everywhere (inside the class, by child classes, and from outside the class).

  • This is the default visibility if no modifier is specified.

class Car { public $brand;
public function setBrand($brand) { $this->brand = $brand; } } $car = new Car();
$car->setBrand("Toyota");
echo $car->brand;
// Accessible: prints "Toyota"

2. Protected

  • Accessible within the class itself and by classes derived from that class (subclasses), but not from outside the class.

class Vehicle { protected $speed = 0;
protected function accelerate() { $this->speed += 10; } } class Car extends Vehicle { public function increaseSpeed() { $this->accelerate(); // OK: accessed within subclass } } $car = new Car(); $car->increaseSpeed(); // OK // $car->accelerate(); //
Error: cannot access protected method from outside

3. Private

  • Accessible only within the class that defines it, not even by subclasses.

class Engine { private $status = "off";
private function start() { $this->status = "on"; }
public function turnOn() { $this->start(); // OK } } class DieselEngine extends Engine {
public function ignite() { // $this->start(); // Error: Cannot access private method } } $engine = new Engine();
$engine->turnOn(); // OK // $engine->start();
// Error: Cannot access private method

Summary Table

Modifier Class Itself Subclasses Outside Class
public
protected
private