How can Dependency Injection Pattern or a Dependency Container help in managing global variables and dependencies in PHP applications?

Global variables and dependencies in PHP applications can lead to tightly coupled code, making it difficult to test and maintain. By using the Dependency Injection Pattern or a Dependency Container, you can easily manage dependencies and avoid the use of global variables, resulting in more modular and testable code.

// Using Dependency Injection Pattern

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    }

    public function query($sql) {
        return $this->connection->query($sql);
    }
}

class UserRepository {
    private $database;

    public function __construct(Database $database) {
        $this->database = $database;
    }

    public function getUsers() {
        return $this->database->query("SELECT * FROM users")->fetchAll();
    }
}

$database = new Database('localhost', 'username', 'password', 'database');
$userRepository = new UserRepository($database);
$users = $userRepository->getUsers();