How can dependency injection be effectively utilized in PHP when working with type validation in classes?
When working with type validation in classes in PHP, dependency injection can be effectively utilized by injecting the dependencies into the class constructor. This allows for better decoupling of dependencies and makes the code more testable and maintainable.
class Database {
private $connection;
public function __construct(PDO $connection) {
$this->connection = $connection;
}
public function query($sql) {
// Query database using $this->connection
}
}
// Usage
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
$database->query('SELECT * FROM users');