What are the advantages of using a class as a wrapper around an array for configuration in PHP?
Using a class as a wrapper around an array for configuration in PHP allows for better organization, encapsulation, and reusability of configuration settings. It also provides a clear interface for accessing and modifying configuration values, making the code more maintainable and easier to understand.
class Configuration {
private $config;
public function __construct(array $config) {
$this->config = $config;
}
public function get($key) {
return $this->config[$key] ?? null;
}
public function set($key, $value) {
$this->config[$key] = $value;
}
}
// Example usage
$configArray = [
'database_host' => 'localhost',
'database_name' => 'my_database',
'username' => 'admin',
'password' => 'password123'
];
$config = new Configuration($configArray);
echo $config->get('database_host'); // Output: localhost
$config->set('database_host', '127.0.0.1');
echo $config->get('database_host'); // Output: 127.0.0.1