PHP:AutoLoader是否可以在单个php文件中加载多个类? [英] PHP: Is AutoLoader able to load multiple class in a single php file?
问题描述
自动加载类的引用:
许多编写面向对象应用程序的开发人员创建了一个PHP每个类定义的源文件.最大的烦恼之一是必须在开始时写一长串所需的清单每个脚本(每个类一个).
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).
在PHP 5中,这不再是必需的.spl_autoload_register()函数注册任意数量的自动加载器,从而启用类和如果当前没有自动加载的接口定义.通过注册自动加载器,PHP得到了最后的机会在出现错误之前加载类或接口.
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文件中有多个类,该代码适合自动加载吗?还是我必须使用 require filepath
语句?
Here comes the question, what if there are multiple classes in a single php file, is it suitable for autoload usage? or do I have to use require filepath
statement?
例如,我在Protobuf \ Client.php下有一个协议文件:
For example, I have a protocol file under Protobuf\Client.php:
<?php
namespace Protobuf;
class A {
...
}
class B {
...
}
推荐答案
您必须具有一些复杂的功能,才能从名为 Client.php
的文件中自动加载这些类.这个想法是将您的 namespace \ classname
转换为 directory \ filename.php
You would have to have some complex function to autoload those classes from the file named Client.php
. The idea is to translate your namespace\classname
into a directory\filename.php
在这种情况下,您需要将文件命名为 A.php
,然后在调用 new Protobuf \ A()
时会找到它.否则,您将不得不创建一个过于复杂的自动加载器.
In this instance you would need to name your file A.php
then when you call new Protobuf\A()
it will find it. Otherwise you will have to create an overly-complex autoloader.
假设您创建了自动加载器,以便找到 A
类,然后可以在同一文件上具有 B
,但前提是您已经自动加载了 A
,否则您必须做一些算法才能知道 A
和 B
在同一页面上.
Let's say you do create the autoloader so it finds the A
class, then you can have B
on the same file, but only if you have already autoloaded A
otherwise you have to make some algorythm to know that A
and B
are on the same page.
我将执行上述模式或 Magento 之类的应用所采用的模式,该模式通过替换下划线将类名转换为目录路径:
I would do the above pattern or the pattern adopted by apps like Magento that turn class names into directory paths by replacing underscores:
$class = new Core_Classes_MyClass_Client();
您的自动加载器将替换下划线并加载:
Your autoloader would replace the underscores and will load:
Core/Classes/MyClass/Client.php //or similar scheme
这对我来说是一种简单的方法,但是我更喜欢使用名称空间和类.上面的方法目前并不受欢迎,从命名的角度来看,很容易混淆,因为很多类可能位于同一文件夹中,或者实际上嵌套在子文件夹中.您可能会为类获得一些很长的命名.
This to me is an easy way to do it, but I prefer using namespace and class. The above method is not in favor at the moment and from a naming standpoint, very easy to get mixed up since a lot of classes may be in the same folder or nested really deep into sub folders. You could get some really long naming for classes.
这篇关于PHP:AutoLoader是否可以在单个php文件中加载多个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!