[英]Replacement for PHP's __autoload function?
我已经阅读过关于在需要时动态加载类文件的内容,如下所示:
function __autoload($className)
{
include("classes/$className.class.php");
}
$obj = new DB();
当你创建该类的一个新实例时,它会自动加载DB.class.php
,但我也读过几篇文章说使用它是不好的,因为它是一个全局函数和你带入项目的任何库一个__autoload()
函数会弄乱它。
那么有人知道解决方案吗? 也许另一种方法可以达到与__autoload()
相同的效果? 在找到合适的解决方案之前,我将继续使用__autoload()
因为它不会开始成为问题,直到您引入库等。
谢谢。
我已经使用以下代码来使用spl_autoload_register,如果它不存在则会降级,并且还处理使用__autoload的库,您需要包含它。
//check to see if there is an existing __autoload function from another library
if(!function_exists('__autoload')) {
if(function_exists('spl_autoload_register')) {
//we have SPL, so register the autoload function
spl_autoload_register('my_autoload_function');
} else {
//if there isn't, we don't need to worry about using the stack,
//we can just register our own autoloader
function __autoload($class_name) {
my_autoload_function($class_name);
}
}
} else {
//ok, so there is an existing __autoload function, we need to use a stack
//if SPL is installed, we can use spl_autoload_register,
//if there isn't, then we can't do anything about it, and
//will have to die
if(function_exists('spl_autoload_register')) {
//we have SPL, so register both the
//original __autoload from the external app,
//because the original will get overwritten by the stack,
//plus our own
spl_autoload_register('__autoload');
spl_autoload_register('my_autoload_function');
} else {
exit;
}
}
因此,该代码将检查现有的__autoload函数,并将其添加到堆栈以及您自己的函数(因为spl_autoload_register将禁用正常的__autoload行为)。
您可以使用spl_autoload_register()
,将任何现有的__autoload()
魔法添加到堆栈中。
function my_autoload( $class ) {
include( $class . '.al.php' );
}
spl_autoload_register('my_autoload');
if( function_exists('__autoload') ) {
spl_autoload_register('__autoload');
}
$f = new Foo;
正确的方法是使用spl_autoload_register
。 要保存某些第三方介绍的__autoload
函数,您也可以将该函数放在autoloader-stack上:
if (function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
使用spl_autoload_register而不是__autoload。 这将允许您将自动加载功能添加到堆栈中。
你可以使用Zend_Loader 。 (假设您可以使用Zend Framework ...)
您可以做的最好的事情是定义自己的对象,负责为您编程的任何子系统进行自动加载。
例如:
class BasketAutoloader
{
static public function register()
{
spl_autoload_register(array(new self, 'autoload'));
}
public function autoload($class)
{
require dirname(__FILE__).'/'.$class.'.php';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.