How can dependency injection be used to pass a MySQLi object to a PHP class for database operations?

To pass a MySQLi object to a PHP class for database operations using dependency injection, you can create a constructor in the class that accepts the MySQLi object as a parameter. This way, the MySQLi object can be injected into the class when it is instantiated, allowing the class to interact with the database without directly creating a new MySQLi object within the class.

<?php

class DatabaseOperations {
    private $mysqli;

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

    public function fetchData() {
        // Use $this->mysqli to perform database operations
    }
}

// Create a MySQLi object
$mysqli = new mysqli("localhost", "username", "password", "database");

// Instantiate the class with the MySQLi object injected
$databaseOperations = new DatabaseOperations($mysqli);

// Now you can call methods on $databaseOperations to interact with the database
$databaseOperations->fetchData();

?>