How can dependency injection be implemented in PHP classes?
Dependency injection in PHP classes can be implemented by passing the dependent objects or services as constructor parameters. This allows for better flexibility, testability, and decoupling of dependencies within the class.
class Database {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
public function query($sql) {
// Use $this->connection to execute the query
}
}
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
Related Questions
- What are the potential security risks of storing passwords in plaintext in PHP config files?
- Is it necessary to declare variables as attributes in PHP classes, or can they be used without prior declaration?
- Is it recommended to store directory entries in an array and then sort them, or is there a more efficient method?