Encapsulation in PHP is a fundamental principle of object-oriented programming that involves the bundling of data and methods within a single unit, called a class, and restricting access to the data through public, protected, and private access modifiers.
The main idea behind encapsulation is to provide a way to protect the data and methods of an object from being accessed or modified by code outside of the class, ensuring that the internal state of the object is consistent and valid.
In PHP, encapsulation is achieved through access modifiers, which determine the level of access to the data and methods of an object. There are three types of access modifiers:
- Public: Data and methods marked as public are accessible from anywhere, both inside and outside of the class.
- Protected: Data and methods marked as protected are accessible only within the class and its subclasses.
- Private: Data and methods marked as private are accessible only within the class.
Here’s an example of encapsulation in PHP:
class Car {
private $color;
protected $model;
public function setColor($color) {
$this->color = $color;
}
public function setModel($model) {
$this->model = $model;
}
public function getInfo() {
return "This car is a " . $this->color . " " . $this->model;
}
}
$car = new Car();
$car->setColor('red');
$car->setModel('BMW');
echo $car->getInfo(); // Output: This car is a red BMW
In this example, the properties “color” and “model” are encapsulated within the “Car” class, and can only be accessed or modified through the public methods “setColor”, “setModel”, and “getInfo”. This ensures that the internal state of the “Car” object is always consistent and valid, and can’t be accidentally modified from outside the class.