Skip to content

Instantly share code, notes, and snippets.

@kbjr
Created August 1, 2010 08:11
Show Gist options
  • Save kbjr/503100 to your computer and use it in GitHub Desktop.
Save kbjr/503100 to your computer and use it in GitHub Desktop.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Const_class {
protected static $data = array();
public function __construct()
{
self::$data = array(
// Any initial data
);
}
// value getter
public function __get($name)
{
if (array_key_exists($name, self::$data))
{
return self::$data[$name];
}
else
{
return null;
}
}
// callback getter
public function __call($name, $args)
{
if (array_key_exists($name, self::$data))
{
return call_user_func_array(self::$data[$name], $args);
}
else
{
return null;
}
}
// value setter
public function define($name, $value)
{
if (! array_key_exists($name, self::$data))
{
self::$data[$name] = $value;
}
}
}
class Const_holder {
protected static $const = null;
static function &get()
{
if (self::$const === null)
self::$const = new Const_class;
return self::$const;
}
}
function &C() { return Const_holder::get(); }
/*
|--------------------------------------------------------------------------
| Demo Time !!! :D
|--------------------------------------------------------------------------
|
*/
// define some "constants"
C()->define('MY_CONST', 'MY_VALUE');
C()->define('MY_ARRAY', array(1, 2, 3, 4));
C()->define('MY_FUNC', function() { echo 'Hello World!'; });
// now read them
echo C()->MY_CONST;
print_r( C()->MY_ARRAY );
C()->MY_FUNC();
/* End of Gist */
@kbjr
Copy link
Author

kbjr commented Aug 1, 2010

I needed some more flexible "constants" ... :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment