How can PHP developers handle database access in one class without using global variables in another class?

When PHP developers need to handle database access in one class without using global variables in another class, they can achieve this by passing an instance of the database connection class to the class that needs it. This can be done through dependency injection, where the class that requires the database connection accepts it as a parameter in its constructor or through a setter method.

// Database connection class
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 that needs database access
class DataHandler {
    private $db;

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

    public function fetchData() {
        $connection = $this->db->getConnection();
        // Use $connection to fetch data from the database
    }
}

// Usage
$database = new Database('localhost', 'username', 'password', 'database_name');
$dataHandler = new DataHandler($database);
$dataHandler->fetchData();