In PHP, access modifiers are keywords that define the visibility or accessibility of properties and methods within a class. They control how properties and methods can be accessed or modified from outside the class. PHP has three main access modifiers:
Properties:
class ClassName {
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
}
class ClassName {
public function publicMethod() {
// Code
}
protected function protectedMethod() {
// Code
}
private function privateMethod() {
// Code
}
}
Example:
class Car {
public $brand; // Public property
protected $model; // Protected property
private $price; // Private property
public function __construct($brand, $model, $price) {
$this->brand = $brand;
$this->model = $model;
$this->price = $price;
}
public function displayInfo() {
echo "Brand: {$this->brand}, Model: {$this->model}, Price: {$this->price}
";
}
public function setPrice($newPrice) {
$this->price = $newPrice;
}
protected function getModel() {
return $this->model;
}
private function getPrice() {
return $this->price;
}
}
// Creating an object of the Car class
$car1 = new Car("Toyota", "Camry", 25000);
// Accessing public properties and methods
echo "Brand: " . $car1->brand . "
"; // Output: Brand: Toyota
$car1->displayInfo(); // Output: Brand: Toyota, Model: Camry, Price: 25000
// Accessing protected and private properties and methods
// This will result in errors because they cannot be accessed from outside the class
// echo "Model: " . $car1->model; // Error: Cannot access protected property
// echo "Price: " . $car1->price; // Error: Cannot access private property
// echo "Model: " . $car1->getModel(); // Error: Cannot access protected method
// echo "Price: " . $car1->getPrice(); // Error: Cannot access private method
// Accessing protected method within a subclass (extends Car)
class LuxuryCar extends Car {
public function getLuxuryModel() {
return "Luxury Model: " . $this->getModel(); // Accessing protected method from parent
}
}
$luxuryCar = new LuxuryCar("BMW", "7 Series", 100000);
echo $luxuryCar->getLuxuryModel(); // Output: Luxury Model: 7 Series
In this example:
Access modifiers help in encapsulation, allowing you to control access to properties and methods, which is essential for maintaining the integrity of the class and preventing unintended modifications.