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();
Keywords
Related Questions
- What potential issues can arise when printing PDF files directly from a browser using fpdf in PHP, compared to printing through a PDF viewer like Adobe Reader?
- How can one ensure that variables are properly sanitized and not relying on register_globals being on when writing PHP code?
- What is the difference between using "endwhile" and curly braces in PHP loops?