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 some best practices for handling line breaks and formatting in text output on a webpage using PHP functions like nl2br()?
- What are the recommended coding conventions and syntax guidelines for writing SQL queries in PHP to ensure compatibility and readability?
- How can PHP scripts be used in conjunction with user-owned domains to maintain a consistent URL structure?