How can arrays with multidimensional data be effectively passed as configurations to PHP classes?
When passing multidimensional arrays as configurations to PHP classes, it is best to use associative arrays where keys represent configuration names and values represent configuration values. This allows for easy access to specific configurations within the class. To pass the multidimensional array to the class, simply instantiate the class and pass the array as an argument to the class constructor.
class Configurations {
private $configurations;
public function __construct($configurations) {
$this->configurations = $configurations;
}
public function getConfig($key) {
return $this->configurations[$key];
}
}
$configurationsArray = [
'database' => [
'host' => 'localhost',
'username' => 'root',
'password' => 'password'
],
'api' => [
'key' => '123456'
]
];
$configurations = new Configurations($configurationsArray);
echo $configurations->getConfig('database')['host']; // Output: localhost