How can implementing Dependency Injection instead of static methods improve the flexibility and maintainability of PHP code, especially when dealing with object creation and manipulation?
Using Dependency Injection instead of static methods allows for better flexibility and maintainability in PHP code because it decouples the code from specific implementations, making it easier to swap out dependencies and test components in isolation.
class Database {
private $connection;
public function __construct(Connection $connection) {
$this->connection = $connection;
}
public function query($sql) {
return $this->connection->query($sql);
}
}
class Connection {
public function query($sql) {
// Database connection logic here
}
}
$connection = new Connection();
$database = new Database($connection);
$result = $database->query("SELECT * FROM table");