How can dependencies between classes and database connections be managed efficiently in PHP?

To manage dependencies between classes and database connections efficiently in PHP, you can use dependency injection. This involves passing the necessary dependencies (such as a database connection object) to the classes that need them, rather than creating the dependencies within the classes themselves. This promotes better code reusability, testability, and flexibility in your application.

<?php

class DatabaseConnection {
    // Database connection details
}

class UserRepository {
    private $db;

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

    // Other methods using $this->db
}

// Usage
$db = new DatabaseConnection();
$userRepository = new UserRepository($db);