Encapsulation in PHP

Encapsulation is one of the pillars of object-oriented programming (OOP) and refers to the bundling of data and the methods that operate on that data into a single unit called an object. It allows you to hide the internal implementation details of an object and control access to its properties and methods.

In PHP, encapsulation can be achieved using visibility modifiers, which determine the accessibility of properties and methods within a class. PHP provides three visibility modifiers:

Public (public):

Public visibility allows properties and methods to be accessed from anywhere, both within the class and outside the class.

class MyClass {
    public $publicProperty;

    public function publicMethod() {
        // Method implementation
    }
}

$obj = new MyClass();
$obj->publicProperty = 'Value';  // Accessing public property
$obj->publicMethod();            // Calling public method

Private (private):

Private visibility restricts the access of properties and methods to only within the class where they are defined. They cannot be accessed from outside the class or even from derived classes.

class MyClass {
    private $privateProperty;

    private function privateMethod() {
        // Method implementation
    }
}

$obj = new MyClass();
$obj->privateProperty = 'Value';  // Error: Cannot access private property
$obj->privateMethod();            // Error: Cannot call private method

Protected (protected):

Protected visibility allows properties and methods to be accessed within the class where they are defined and in derived classes. They cannot be accessed from outside the class or from unrelated classes.

class MyClass {
    protected $protectedProperty;

    protected function protectedMethod() {
        // Method implementation
    }
}

class ChildClass extends MyClass {
    public function accessProtected() {
        $this->protectedProperty = 'Value';  // Accessing protected property
        $this->protectedMethod();            // Calling protected method
    }
}

$child = new ChildClass();
$child->accessProtected();

Encapsulation allows you to enforce data integrity by controlling how properties are accessed and modified. It also provides a clear interface for interacting with objects, hiding the implementation details and protecting the internal state of objects. By using proper visibility modifiers, you can ensure that only the necessary properties and methods are accessible to external code, promoting code maintainability and reducing the likelihood of unintended modifications or errors.