How can global variables be avoided in PHP code to improve readability and maintainability?

Global variables can be avoided in PHP code by using object-oriented programming principles such as encapsulation and dependency injection. By creating classes and objects to encapsulate data and behavior, you can reduce the reliance on global variables, leading to code that is more readable and maintainable.

class User {
    private $username;
    
    public function setUsername($username) {
        $this->username = $username;
    }
    
    public function getUsername() {
        return $this->username;
    }
}

$user = new User();
$user->setUsername('john_doe');
echo $user->getUsername();