Advertisement

Google Ad Slot: content-top

PHP OOP - Access Modifiers


PHP - Access Modifiers


Access modifiers in PHP control the visibility of class properties and methods.


PHP provides three types of access modifiers:


  • public - Accessible from anywhere (inside or outside the class). This is default
  • protected - Accessible within the class and inherited (child) classes only
  • private - Accessible only inside the class that defines it


In the following example we have added three different access modifiers to three properties (brand, engine, and price). Here, if you try to access the brand property it will work fine (because the brand property is public, and can be accessed from everywhere). However, if you try to access the engine or color property it will result in a fatal error (because the engine and color property are protected and private):

Example
<?php
class Car {
public $brand = "Toyota"; // Can be accessed from anywhere
protected $engine = "V8"; // Can be accessed within class and subclasses
private $price = "$30,000"; // Can only be accessed within this class
public function showDetails() {
return "Brand: $this->brand, Engine: $this->engine, Price: $this->price";
}
}
$myCar = new Car();
echo $myCar->brand; // Allowed (public)
// echo $myCar->engine; // Error (protected)
// echo $myCar->price; // Error (private)
echo "<br>" . $myCar->showDetails(); // Allowed (public method)
?>
Try it yourself