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();
?>
Related Questions
- Can PHP scripts be set to run automatically without manual intervention?
- How can regular expressions be utilized in PHP to efficiently parse and extract data from text files, such as in the provided example?
- What is the best method to read an object from a database that has a collection attribute in PHP?