How can dependencies be managed effectively when instantiating objects within a class in PHP, particularly when working with database connections like mysqli?

When instantiating objects within a class in PHP, particularly when working with database connections like mysqli, it is important to manage dependencies effectively to ensure clean and maintainable code. One way to achieve this is by using dependency injection, where the dependencies are passed into the class constructor or methods rather than being created inside the class itself. This allows for better separation of concerns and makes it easier to test and reuse the code.

<?php

class Database {
    private $connection;

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

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

$mysqli = new mysqli('localhost', 'username', 'password', 'database');
$database = new Database($mysqli);

$result = $database->query('SELECT * FROM table');

?>