In PHP development, what are the best practices for passing database objects to classes and methods for efficient and scalable code?

When passing database objects to classes and methods in PHP development, it is best practice to use Dependency Injection to decouple the database connection from the class itself. This allows for better scalability and testability of the code by making it easier to switch out different database connections or mock objects for testing.

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    }

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

class User {
    private $db;

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

    public function getUsers() {
        $query = "SELECT * FROM users";
        $stmt = $this->db->getConnection()->query($query);
        return $stmt->fetchAll();
    }
}

// Usage
$database = new Database('localhost', 'root', 'password', 'mydatabase');
$user = new User($database);
$users = $user->getUsers();