How does Dependency Injection play a role in avoiding static dependencies like Singletons in PHP?
Static dependencies like Singletons can lead to tightly coupled code and make unit testing difficult. Dependency Injection helps avoid this by allowing dependencies to be passed into a class from the outside, making the code more flexible and easier to test.
// Bad example using a Singleton
class Database {
private static $instance;
public static function getInstance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
// Good example using Dependency Injection
class Database {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
}
// Usage of Dependency Injection
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
Related Questions
- How can PHP developers ensure that substr_count accurately counts occurrences of specific words in a string, especially when words are not consistently separated by spaces?
- What are the key differences between mysql and mysqli functions in PHP that developers should be aware of?
- What potential risks are involved in creating and using public proxy servers?