PHP: AutoLoader 是否能够在单个 php 文件中加载多个类?

标签 php autoload

引自 Autoloading Classes :

Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.

问题来了,如果一个php文件中有多个class,适合autoload使用吗?还是我必须使用 require filepath 语句?

比如我在Protobuf\Client.php下有一个协议(protocol)文件:

<?php

namespace Protobuf;
class A {
...
}
class B {
...
}

最佳答案

您必须有一些复杂的函数才能从名为 Client.php 的文件中自动加载这些类。这个想法是将您的 namespace\classname 翻译成 directory\filename.php

在这种情况下,您需要将文件命名为 A.php,然后当您调用 new Protobuf\A() 时,它会找到它。否则,您将不得不创建一个过于复杂的自动加载器。

假设您确实创建了自动加载器,因此它找到了 A 类,然后您可以在同一个文件上拥有 B,但前提是您已经自动加载了 >A 否则你必须做一些算法才能知道 AB 在同一页面上。

我会采用上述模式或像 Magento 这样的应用程序采用的模式,通过替换下划线将类名转换为目录路径:

$class = new Core_Classes_MyClass_Client();

您的自动加载器将替换下划线并加载:

Core/Classes/MyClass/Client.php //or similar scheme

这对我来说是一种简单的方法,但我更喜欢使用命名空间和类。上面的方法目前并不受欢迎,从命名的角度来看,很容易混淆,因为很多类可能在同一个文件夹中,或者嵌套在子文件夹中。您可以获得一些非常长的类命名。

关于PHP: AutoLoader 是否能够在单个 php 文件中加载多个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37982012/

相关文章:

php - PHP/Python/Etc 中内置函数的 ctags 信息

php - 向 MySQL 数据库添加多个标签

ruby-on-rails - 我如何告诉 Rails 从顶级目录自动加载命名空间模型?

php - 为什么 Mac OSX 在使用 Docker Desktop for Mac 时仍然不区分大小写

php - Composer,PSR-4 自动加载迭代

PHP 异步函数调用与 AJAX

php - 代码点火器 3 : where clause gives an ambiguous column error

php - Symfony Profiler 的日志数据

namespaces - 我不能在 Symfony 1.4 中使用来自 Symfony2 的 Autoloader 来加载这个命名空间类

php - Laravel 5 - 将用户模型移动到应用程序/模型导致自动加载问题