How can Dependency Injection be used to add instances to a class in PHP?
Dependency Injection is a design pattern used to inject dependencies into a class instead of the class creating its dependencies internally. This promotes loose coupling and makes the code more testable and maintainable. In PHP, you can achieve Dependency Injection by passing instances of dependencies to a class through its constructor or setter methods.
// Example of using Dependency Injection in PHP
class Database {
public function query($sql) {
// Database query logic
return "Query executed: $sql";
}
}
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function getUserById($id) {
$sql = "SELECT * FROM users WHERE id = $id";
return $this->db->query($sql);
}
}
// Usage
$db = new Database();
$userRepository = new UserRepository($db);
echo $userRepository->getUserById(1);
Related Questions
- What is the significance of using correct punctuation in PHP code, especially when concatenating strings?
- How can the "Strict Standards: Only variables should be passed by reference" error be resolved in PHP?
- What is the significance of the 403 Error Code in PHP when trying to send an Image Code via post?