我正在学习高级 PHP 标准并尝试实现新的有用的方法。早些时候我使用 __autoload
只是为了逃避在每个页面上包含多个文件,但最近我看到了关于 __autoload manual
的提示
spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.
但我真的不知道如何实现 spl_autoload
和 spl_autoload_register
最佳答案
spl_autoload_register()
允许您注册多个函数(或来自您自己的 Autoload 类的静态方法),PHP 将把它们放入堆栈/队列并在声明“新类”时按顺序调用。
例如:
spl_autoload_register('myAutoloader');
function myAutoloader($className)
{
$path = '/path/to/class/';
include $path.$className.'.php';
}
//-------------------------------------
$myClass = new MyClass();
在上面的示例中,“MyClass”是您尝试实例化的类的名称,PHP 将此名称作为字符串传递给 spl_autoload_register()
,这样您就可以获取变量并使用它来“包含”适当的类/文件。因此,您不需要特别通过 include/require 语句包含该类...
只需像上面的示例一样调用您要实例化的类,并且由于您注册了一个自己的函数(通过 spl_autoload_register()
),该函数将确定所有类的位置, PHP 将使用该函数。
使用 spl_autoload_register()
的好处是,与 __autoload()
不同,您不需要在创建的每个文件中实现自动加载功能。 spl_autoload_register()
还允许您注册多个自动加载函数以加快自动加载并使其更容易。
例子:
spl_autoload_register('MyAutoloader::ClassLoader');
spl_autoload_register('MyAutoloader::LibraryLoader');
spl_autoload_register('MyAutoloader::HelperLoader');
spl_autoload_register('MyAutoloader::DatabaseLoader');
class MyAutoloader
{
public static function ClassLoader($className)
{
//your loading logic here
}
public static function LibraryLoader($className)
{
//your loading logic here
}
关于 spl_autoload ,手册指出:
This function is intended to be used as a default implementation for
__autoload()
. If nothing else is specified andspl_autoload_register()
is called without any parameters then this functions will be used for any later call to__autoload()
.
更实际地说,如果您的所有文件都位于一个目录中,并且您的应用程序不仅使用 .php 文件,还使用带有 .inc 扩展名的自定义配置文件,那么您可以使用的一种策略是添加您的包含 PHP 包含路径的所有文件的目录(通过 set_include_path()
)。
由于您还需要配置文件,因此您可以使用 spl_autoload_extensions()
列出您希望 PHP 查找的扩展。
例子:
set_include_path(get_include_path().PATH_SEPARATOR.'path/to/my/directory/');
spl_autoload_extensions('.php, .inc');
spl_autoload_register();
由于 spl_autoload 是 __autoload()
魔术方法的默认实现,当您尝试实例化一个新类时,PHP 将调用 spl_autoload。
希望这会有所帮助...
关于php - 什么是自动加载;如何使用 spl_autoload、__autoload 和 spl_autoload_register?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651509/