Passing Arguments as an Associative Array to a Function

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.

On line 21 we assign the value of the setting – it is here that the default setting is overwritten. The class would be used as follows:

include 'classes/setOptions.php';

/*
Choose the settings to overwrite. You
could overwite a single setting if required
*/
$settings = array(
    'temp' => '/temp/',
    'upload' => '/user/upload/',
    'cache_time' => '432000',
    'cache_file' => 'my_users.txt',
    'cache_status' => 5
);

/*
Create new instance of our class
and pass the array of setting(s) in the
constructor
*/
$myObj = new setOptions($settings);

It is now possible to use any of the class variables we have just overwritten using the follow method, in any of our functions:

function cacheUsers() {
 $cachefile = $this->temp . $this->cache_file
 $cachetime = $this->cache_time;
 if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile)))  {
  // Do something!
 }
}

With a little modification, you could make your own classes extend the setOptions class:

class myCustomClass extends setOptions {

    function ___constrct($options = array())
    {
       parent::__construct($options);
    }

   function myDebuggingStuff() {
        echo $this->cache_time;
    }

}

and in the controller file:

include 'model/setOptions.php';
include 'model/myCustomClass.php';

$settings = array(
    'temp' => '/temp/',
    'upload' => '/user/uploads_custom_location_overwritten/',
    'cache_time' => '4320004534',
    'cache_status' => 5
);

$myObj = new myCustomClass($settings);
$myObj->myDebuggingStuff();
// prints '/user/uploads_custom_location_overwritten/'

All the source files (with further source code commenting) can be downloaded from – here.

Published by

Rob Allport

Web Developer based in Stoke-on-Trent Staffordshire Google+ - Twitter

4 thoughts on “Passing Arguments as an Associative Array to a Function”

  1. Hey there would you mind stating which blog platform you’re working with? I’m going to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique. P.S My apologies for being off-topic but I had to ask!


  2. Sniper Forex:

    Hey there would you mind stating which blog platform you’re working with? I’m going to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I’m looking for something completely unique. P.S My apologies for being off-topic but I had to ask!

    It’s just WordPress 😉

  3. Its good trick to send the array in the funtion as an argument.

  4. Great article – can’t stop to write more, must dash because you’ve inspired me to go create something – thank you!

Comments are closed.