How does encapsulation work in PHP classes and why is it beneficial?

Encapsulation in PHP classes refers to the concept of bundling the data (properties) and methods (functions) that operate on the data into a single unit or class. This helps in restricting access to certain properties or methods from outside the class, ensuring that the internal state of the object is not accidentally modified. Encapsulation promotes data hiding and reduces the risk of unintended interference, making the code more maintainable and easier to understand.

<?php

class User {
    private $username;
    private $email;

    public function setUsername($username) {
        $this->username = $username;
    }

    public function getEmail() {
        return $this->email;
    }
}

$user = new User();
$user->setUsername("JohnDoe");
echo $user->username; // This will result in an error since $username is private
echo $user->getEmail(); // This will correctly return the email
?>