What are the best practices for constructor injection in PHP?
Constructor injection is a best practice in PHP for injecting dependencies into a class through its constructor. This helps in making the class more testable, maintainable, and flexible. By passing dependencies through the constructor, we can ensure that the class has all the necessary dependencies when it is instantiated.
class DatabaseConnection {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function query($sql) {
return $this->db->query($sql);
}
}
$db = new Database();
$connection = new DatabaseConnection($db);
$result = $connection->query("SELECT * FROM users");
Keywords
Related Questions
- What are the best practices for handling integer values in prepared statements with PDO?
- What are common mistakes to watch out for when binding parameters in prepared statements in PHP?
- How can PHP be used to retrieve and display data from a MySQL database on a webpage, such as dynamically changing content like a user's name?