【问题标题】:What does everyone mean by: 'spl:_autoload() is default implementation of __autoload()'每个人的意思是什么:'spl:_autoload() 是 __autoload()' 的默认实现
【发布时间】:2018-04-28 12:13:16
【问题描述】:

我对 php 自动加载的一件事感到困惑:spl_autoload() 函数。在每个答案中,我发现这个函数是__autoload 的默认实现。 PHP不应该自己定义__autoload()的默认实现,然后如果我明确创建__autoload(),它会覆盖它吗?

如果我没有在我的 php 文件中明确定义 __autoload() 函数,会有默认实现吗? spl_autoload()是某种内部函数吗,如果是,那为什么在php doc里面呢?

(如果它不是内部函数)在每个 spl_autoload() 示例中都没有对该函数的任何调用,只有 spl_autoload_register 没有参数,spl_autoload_extensions 等等。为什么这样?我错过了什么?

引用自:What is Autoloading; How do you use spl_autoload, __autoload and spl_autoload_register?

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 一个新的类。

所以如果我不调用spl_autoload_register(),它就不会注册默认实现? spl_autoload 是否查看 spl_autoload_extensions(); 设置的扩展名,然后从包含路径导入所有具有这些扩展名的文件?重复前面提到的问题:spl_autoload()是内部函数吗?

我知道__autoload() 已被弃用,我应该使用spl_autoload_register()。我只是想确保我知道这一切是如何运作的。

谢谢。

【问题讨论】:

标签: php autoloader spl spl-autoloader


【解决方案1】:

前面提到的重复问题:spl_autoload()是内部函数吗?

如果您不传递参数,那只是spl_autoload_register 的“默认值”。如果您愿意,也可以单独调用此函数。 spl_autoload 的行为可以通过spl_autoload_extensions 和set_include_path 进行配置。

在内部spl_autoload 将全限定类名(fqcn) 作为查找类实现的路径。 (也许用字符串替换目录分隔符)。然后,它在给定文件之后的 class_include_path 的每个元素中搜索。

spl_autoload_extensions(".php");
spl_autoload_register();
$foo = new \foo\Bar();
// now spl_autoload tries to load the file foo/Bar.php inside your class path.

如果您需要更复杂的东西,您必须为自动加载器创建自己的回调。 IE。像这样的

spl_autoload_register(function($class) {
    $path = 'classes' . DIRECTORY_SEPERATOR;
    // dont care about case
    $class = strtolower($class);
    // replace _ with DIRECTORY_SEPERATOR
    $name = str_replace('_', DIRECTORY_SEPERATOR, $class);
    // don't care about windows/unix
    $name = str_replace('/', DIRECTORY_SEPERATOR, $name);
    $file = $path . $name . '.php';
    if (file_exists($file)) {
        include ($file);
    }
});

注意:上面的示例不关心spl_autoload_extensions 或set_include_path 的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多