Sometimes is it useful and slightly cleaner to pass arguements to a function via an associative array as opposed to a list of variables. There are a variety of methods to achieve this, such as using PHP’s extract function – but the below is cleaner in my opinion. Please note, the following functionality is common place when using a good MVC framework, or a good CodeIgniter base class. Take a sample PHP class:
class setOptions {
var $temp = '/default_temp/';
var $upload = '/default_upload/';
var $cache_time = '0';
var $cache_status = '0';
var $cache_file = 'users.txt';
function __construct($user_settings)
{
if (is_array($user_settings)) {
foreach($user_settings as $k=>$v) {
$this->assignSetting($k, $v);
}
} else {
die('Config Error!');
}
}
function assignSetting($name, $value)
{
$whitelist = array('temp', 'upload', 'cache_time', 'cache_status', 'cache_file');
if (in_array($name, $whitelist)) {
$property = $name;
$this->$property = $value;
}
}
}
In lines 3 – 6 we set the default values of our settings that are used an our class. We can choose to leave these as they are, or pass the class an array of new setting, to overwrite them.
In line 8 the settings array, as an associative array, is passed to the magic construct function so all the settings are available when the class is called. On line 10, we check to ensure that the data passed to the function is actually an array and on line 11 we simply through each key/value of the array.
On each iteration, the assignSetting function is called (line 17). The function takes a setting name and value as it’s arguements. On line 19 a whitelist of allowed settings is created as an array. Line 20 checks to ensure the setting we are attempting to add is within this whitelist.
Continue reading Passing Arguments as an Associative Array to a Function