What are the best practices for constructor injection in PHP?

Constructor injection is a best practice in PHP for injecting dependencies into a class through its constructor. This helps in making the class more testable, maintainable, and flexible. By passing dependencies through the constructor, we can ensure that the class has all the necessary dependencies when it is instantiated.

class DatabaseConnection {
    private $db;

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

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

$db = new Database();
$connection = new DatabaseConnection($db);
$result = $connection->query("SELECT * FROM users");