How can Dependency Injection be used to provide configuration settings to a class in PHP?
When using Dependency Injection in PHP, configuration settings can be passed to a class by injecting a configuration object or array into the class constructor. This allows the class to access the configuration settings without directly depending on a global configuration object or file, making the class more flexible and testable.
class MyClass {
private $config;
public function __construct(array $config) {
$this->config = $config;
}
public function getConfigValue($key) {
return $this->config[$key] ?? null;
}
}
// Usage
$config = [
'database_host' => 'localhost',
'database_name' => 'mydatabase',
'database_user' => 'root',
'database_pass' => 'password'
];
$myClass = new MyClass($config);
echo $myClass->getConfigValue('database_host'); // Output: localhost