php 什么是自动加载;你如何使用 spl_autoload、__autoload 和 spl_autoload_register?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7651509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:06:11  来源:igfitidea点击:

What is Autoloading; How do you use spl_autoload, __autoload and spl_autoload_register?

phpautoloadspl

提问by diEcho

I am learning advanced PHP standards and trying to implement new and useful methods. Earlier I was using __autoloadjust to escape including multiple files on each page, but recently I have seen a tip on __autoload manual

我正在学习高级 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_register()为自动加载类提供了更灵活的替代方法。出于这个原因,不鼓励使用__autoload()并且将来可能会被弃用或删除。

but I really can't figure out how to implement spl_autoloadand spl_autoload_register

但我真的不知道如何实施spl_autoloadspl_autoload_register

回答by Brownbay

spl_autoload_register()allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared.

spl_autoload_register()允许您注册多个函数(或来自您自己的 Autoload 类的静态方法),PHP 会将这些函数放入堆栈/队列并在声明“新类”时按顺序调用。

So for example:

例如:

spl_autoload_register('myAutoloader');

function myAutoloader($className)
{
    $path = '/path/to/class/';

    include $path.$className.'.php';
}

//-------------------------------------

$myClass = new MyClass();

In the example above, "MyClass" is the name of the class that you are trying to instantiate, PHP passes this name as a string to spl_autoload_register(), which allows you to pick up the variable and use it to "include" the appropriate class/file. As a result you don't specifically need to include that class via an include/require statement...

在上面的示例中,“MyClass”是您尝试实例化的类的名称,PHP 将此名称作为字符串传递给spl_autoload_register(),这允许您选择变量并使用它来“包含”适当的类/文件. 因此,您不需要特别需要通过包含/要求语句包含该类...

Just simply call the class you want to instantiate like in the example above, and since you registered a function (via spl_autoload_register()) of your own that will figure out where all your class are located, PHP will use that function.

只需像上面的示例一样简单地调用您想要实例化的类,并且由于您注册了一个spl_autoload_register()自己的函数(通过),它将找出所有类所在的位置,PHP 将使用该函数。

The benefit of using spl_autoload_register()is that unlike __autoload()you don't need to implement an autoload function in every file that you create. spl_autoload_register()also allows you to register multiple autoload functions to speed up autoloading and make it even easier.

使用的好处spl_autoload_register()是不像__autoload()你不需要在你创建的每个文件中实现自动加载功能。spl_autoload_register()还允许您注册多个自动加载功能以加快自动加载并使其更容易。

Example:

例子:

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
    }


With regards to spl_autoload, the manual states:

关于spl_autoload,手册指出:

This function is intended to be used as a default implementation for __autoload(). If nothing else is specified and spl_autoload_register()is called without any parameters then this functions will be used for any later call to __autoload().

此函数旨在用作__autoload(). 如果未指定任何其他内容并且spl_autoload_register()不带任何参数调用,则此函数将用于以后对 的任何调用__autoload()

In more practical terms, if all your files are located in a single directory and your application uses not only .php files, but custom configuration files with .inc extensions for example, then one strategy you could use would be to add your directory containing all files to PHP's include path (via set_include_path()).
And since you require your configuration files as well, you would use spl_autoload_extensions()to list the extensions that you want PHP to look for.

更实际地说,如果您的所有文件都位于一个目录中,并且您的应用程序不仅使用 .php 文件,还使用扩展名为 .inc 的自定义配置文件,那么您可以使用的一种策略是添加包含所有文件的目录文件到 PHP 的包含路径(通过set_include_path())。
并且由于您还需要配置文件,因此您可以使用spl_autoload_extensions()列出希望 PHP 查找的扩展名。

Example:

例子:

set_include_path(get_include_path().PATH_SEPARATOR.'path/to/my/directory/');
spl_autoload_extensions('.php, .inc');
spl_autoload_register();

Since spl_autoload is the default implementation of the __autoload()magic method, PHP will call spl_autoload when you try and instantiate a new class.

由于 spl_autoload 是__autoload()魔法方法的默认实现,当您尝试实例化一个新类时,PHP 将调用 spl_autoload。

Hope this helps...

希望这可以帮助...

回答by user1974206

Since PHP 5.3, you can use spl_autoload_register()with namespaces, which means that you can organize your project and autoload your php classes without any require or include and without redefining an __autoload()function.

自 PHP 5.3 起,您可以使用spl_autoload_register()命名空间,这意味着您可以组织您的项目并自动加载您的 php 类,而无需任何 require 或 include,也无需重新定义__autoload()函数。

To demonstrate this behaviour, just create a file called index.php :

为了演示这种行为,只需创建一个名为 index.php 的文件:

<?php
spl_autoload_register();
var_dump(new Main\Application);

Then create a folder named Main located right next to the index.php file. Finally, creates a file called Application.php located into Main and paste the following code into it :

然后在 index.php 文件旁边创建一个名为 Main 的文件夹。最后,在 Main 中创建一个名为 Application.php 的文件,并将以下代码粘贴到其中:

<?php namespace Main;
class Application{}

回答by Augusto Santana

Here is the way I do use Autoload. In the given example I wanto to load classes form 3 diferent directories.

这是我使用 Autoload 的方式。在给定的示例中,我想从 3 个不同的目录加载类。

function namespaceAutoload($rawClass){

$class = str_replace('\', DIRECTORY_SEPARATOR, $rawClass);

$possiblePaths[] = '..\sys\class\file.php';
$possiblePaths[] = '..\sys\class\lib\file.php';
$possiblePaths[] = '..\sys\class\class.file.inc.php';

foreach ($possiblePaths as $templatePath) {
    $path = str_replace(["\", "file"], [DIRECTORY_SEPARATOR, $class], $templatePath);
    if (file_exists($path)) {
        require_once "$path";
        break;
    }
} spl_autoload_register("namespaceAutoload"); 

I the given example, the PHP will look for the namespace\class in these three directories using these three different filename formats.

在给定的示例中,PHP 将使用这三种不同的文件名格式在这三个目录中查找 namespace\class。