How can data encapsulation be implemented in PHP classes to avoid global variables?

Data encapsulation in PHP classes can be implemented by using private or protected class properties and public methods to access and modify these properties. This helps avoid the use of global variables by restricting direct access to the class properties from outside the class. By encapsulating the data within the class, you can control how it is accessed and modified, improving code readability and maintainability.

class User {
    private $username;
    private $email;

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

    public function getUsername() {
        return $this->username;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

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

$user = new User();
$user->setUsername('john_doe');
$user->setEmail('john.doe@example.com');

echo $user->getUsername(); // Output: john_doe
echo $user->getEmail(); // Output: john.doe@example.com