What are the best practices for handling dependencies and injection in PHP classes to ensure consistency and avoid errors?

When handling dependencies and injection in PHP classes, it is important to follow best practices to ensure consistency and avoid errors. One way to achieve this is by using dependency injection to pass dependencies into a class rather than instantiating them within the class itself. This promotes code reusability, testability, and separation of concerns.

class Database {
    private $connection;

    public function __construct(PDO $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);
$database->query('SELECT * FROM table');