How can you optimize the handling of classes and database connections when passing objects in PHP?

When passing objects in PHP, it's important to optimize the handling of classes and database connections to prevent memory leaks and improve performance. One way to achieve this is by utilizing dependency injection to pass database connections as dependencies to classes that need them, rather than creating new connections within each class. This approach helps to centralize database connection management and ensures that connections are properly closed after they are no longer needed.

<?php

class Database {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
    }

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

class UserRepository {
    private $db;

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

    public function getUserById($id) {
        $connection = $this->db->getConnection();
        // Query database for user with given ID
    }
}

// Usage
$db = new Database('localhost', 'username', 'password', 'database');
$userRepository = new UserRepository($db);
$userRepository->getUserById(1);

?>