User:Jonathans/rg

register_global
an easy to use function for manually registering global variables from a key-value paired source array, such as $_POST. the function supports callbacks for validating user input on the spot without having to duplicate code in several user-requested scripts.

/* * @title register_global * @desc register a key from a superglobal as a global *      variable in the current context. public domain. * @author jon@fuck.org * @version 1.0 * @param $name      string  key to superglobal. * @param $type      string  typename to cast the value to. * @param $default   mixed   default value to set for new global. * @param $super     &array  reference to superglobal of choice. *                           could be any array with keys, though. * @param $callbacks array   set of functions to modify the data *                           from the superglobal after registering. * @return boolean true if key found in superglobal, false otherwise. *                note that the global is registered in either case. */ function register_global($name,                        &$super,                         $type = null,                         $default = null,                         $callbacks = null) { global ${$name};

// set default value ${$name} = $default;

if (!$type) $type = 'string';

if (isset($super[$name])) {   // get data from superglobal ${$name} = $super[$name];

// typecast settype(${$name}, $type);

// normalize with callback functions if (is_array($callbacks)) foreach($callbacks as $func) ${$name} = call_user_func($func, ${$name});

// default overridden. return true; }

// default value was set. return false; }

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * below are the collection of callback functions to * be used with register_global. */

// use only the first token of the input string. // function rg_tok($input) { return strtok($input, ' +'); }

// force lowercase input. // function rg_lcase($input) { return strtolower($input); }