autoload class

The __autoload() magic function is used to dynamically load classes. Whenever PHP encounters a non-existent class, it will first call the __autoload() function, and only then declare an error. This can be used to load classes on-the-fly.
 
error_reporting (E_ALL);
if (version_compare(phpversion(), '5.1.0', '<') == true) { die ('PHP5.1 Only'); }

// Constants:
define ('DIRSEP', DIRECTORY_SEPARATOR);

// Get site path
$site_path = realpath(dirname(__FILE__) . DIRSEP . '..' . DIRSEP) . DIRSEP;
define ('site_path', $site_path);

$registry = new Registry;

// Set some data
$registry->set ('name', 'Don');

// Get data, using get()
echo $registry->get ('name');

// Get data, using array access
echo $registry['name']

function __autoload($className) {
// Assume that all class files are located in the same dir and subdirs
$fname = str_replace('::', DIRECTORY_SEPARATOR, $className) . '.php';
if(is_file($fname)) {
include_once($fname);
return;
}

$namespace = substr($className, 0, strrpos($className, '::'));
$localClassName = substr($className, strrpos($className, '::') + 2);
if($namespace) {
eval("namespace $namespace;
class $localClassName {
function __construct() {
throw new Exception('Class $namespace::$localClassName not found');
}

static function __callstatic(\$m, \$args) {
throw new Exception('Class $className not found');
}
}");
} else {
eval("class $className {
function __construct() {
throw new Exception('Class $className not found');
}

static function __callstatic(\$m, \$args) {
throw new Exception('Class $className not found');
}
}");
}
}
?>

//Now, to test this, you can use the following code:

vars[$key]) == true) {
throw new Exception('Unable to set var `' . $key . '`. Already set.');
}

$this->vars[$key] = $var;
return true;
}

function get($key) {
if (isset($this->vars[$key]) == false) {
return null;
}

return $this->vars[$key];
}

function remove($var) {
unset($this->vars[$key]);
}

}


Class Registry Implements ArrayAccess {
function offsetExists($offset) {
return isset($this->vars[$offset]);
}

function offsetGet($offset) {
return $this->get($offset);
}

function offsetSet($offset, $value) {
$this->set($offset, $value);
}

function offsetUnset($offset) {
unset($this->vars[$offset]);
}
}

Comments

Popular posts from this blog

Detecting user's screen size and resolution

MySql Slow Queries