该spl_autoload_register()函数可以与 3 种类型的回调一起使用:函数、静态方法和常规方法。与其他类型相比,这三种类型有什么优点/缺点吗?
1641 次
2 回答
2
实际上没有任何重大差异。
一个闭包(定义如下(仅限 PHP 5.3+))永远不能被注销,除非它被保存到一个变量中:
spl_autoload_register(function($class) { ... });
静态方法实际上可以在运行其自动加载器之前自动加载静态类
spl_autoload_register(function($class) {
if ($class === 'AutoLoader') {
var_dump('Auto loading AutoLoader');
class AutoLoader {
public static function autoload($class) {
var_dump(__CLASS__ . ' is loading: ' . $class);
}
}
}
});
spl_autoload_register('AutoLoader::autoload');
Test::func();
// 'Auto loading AutoLoader'
// 'AutoLoader is loading: Test'
虽然,我不知道你为什么要这样做。
静态调用更容易注销。
无论哪种方式,您都应该遵循 PSR0 自动加载标准:https ://gist.github.com/221634
于 2011-12-12T23:46:28.663 回答
0
如果您使用非静态可调用对象,则动态解析文件路径和类命名空间的优势。
class SimpleFactory {
protected $path, $namespace;
function __construct($path, $namespace) {
$this->path = $path;
$this->namespace = $namespace;
spl_autoload_register(array($this, 'autoload'));
}
function __destruct() {
spl_autoload_unregister(array($this, 'autoload'));
}
function produce($name) {
if (class_exists($name, $autoload = true)) {
return new $name();
} else throw new RuntimeException("Unable to produce {$name}");
}
public function autoload($name) {
$class_name = str_replace($this->namespace, '', $name);
$filename = $this->path.$class_name.'.php';
if (file_exists($filename))
require $filename;
}
}
尝试
$a = new SimpleFactory('path1/', 'anames\\');
$a1 = SimpleFactory->produce('a');
get_class($a1) == anames\a
$b = new SimpleFactory('path2/', 'bnames\\');
$b1 = SimpleFactory->produce('a');
get_class($b1) == bnames\a
有关更广泛的示例,请参阅我在Throwing Exceptions in an SPL autoloader? 中的回答?
于 2015-10-01T17:54:54.413 回答