How can dependency injection be implemented in PHP classes?

Dependency injection in PHP classes can be implemented by passing the dependent objects or services as constructor parameters. This allows for better flexibility, testability, and decoupling of dependencies within the class.

class Database {
    private $connection;

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

    public function query($sql) {
        // Use $this->connection to execute the query
    }
}

$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);