[eluser]ntheorist[/eluser]
Here's a little function i'm playing with for storing and retrieving global data for use in views and elsewhere within an application. The point of course isn't to store vast amounts of data, just to collect basic variables in one place, preferences, config, userdata, uri variables etc. The reason i want to use a function instead of using $this->load->vars($array) is mainly to avoid name conflicts within views, but also so i can set vars within constructors and use them in methods/libraries/plugins as well.
it's use is pretty basic too:
Code:
globals('test','123'); // Set test to 123
globals('time',time()); // Set load time, for instance
echo globals('test'); // '123'
// Arrays are flattened with dot-syntax
$page['controller'] = $this->router->fetch_class();
$page['method'] = $this->router->fetch_method();
$page['base'] = base_url();
$page['url'] = current_url();
globals('page', $page);
echo globals('page.method'); // returns current method
echo globals('page.controller');
// Get entire array
print_r(globals());
Here it is. Comments, suggestions, criticisms welcome.
Code:
if ( ! function_exists('globals') )
{
function globals( $name = NULL , $value = NULL )
{
static $globals = array();
if( ! empty($name) )
{
if( empty($value) )
{
return isset( $globals[$name] ) ? $globals[$name] : FALSE;
}
else
{
if( is_array($value) )
{
foreach($value as $key => $v)
{
$globals[$name .'.'.$key] = $v;
}
}
else
{
$globals[$name] = $value;
}
}
}
else
{
return $globals;
}
}
}
n