Access modifiers control where variables and methods can be used.

Types Of Access Modifier 

  1. Public: Can be used anywhere (inside and outside the class). This is the default access modifier in PHP.
  2. Private: Can be used only inside the same class.
  3. Protected: Can be used inside the class and in child classes.

Example:

<?php
class Car {
    public $brand = "Toyota";
    protected $model = "Corolla";
    private $price = "10 Lakh";
    public function show() {
        echo $this->brand . "<br>";
        echo $this->model . "<br>";
        echo $this->price . "<br>";
    }
}
$car = new Car();
echo $car->brand . "<br>";
$car->show();
?>
  • public: $brand - Can be used outside the class echo $car->brand;
  • protected: $model - Cannot be used outside directly, but can be used inside the class or child class
  • private: $price - Can be used only inside the same class