PHP:使用自动加载器时如何获取所有类
我正在使用 composer 来生成自动加载器:
I'm using composer to generate autoloader:
"autoload": {
"psr-4": {
"SomeNamespace\": "src/SomeDir"
}
}
我需要创建实现特定接口的所有类的实例.不使用自动加载器时相当简单,但是 get_declared_classes()
不能很好地与自动加载器配合使用.只有在使用自动加载器实例化后,它才会列出一个类.
I need to create instances of all classes that implement specific interface. It's fairly easy when not using autoloader, however get_declared_classes()
is not playing well with autoloaders. It will list a class only after it was instantiated with autoloader.
推荐答案
如果您不跟踪存在哪些类,那么自动加载将无济于事.
If you don't keep track of which classes exist, autoloading won't help you.
但是,如果您尝试包含所有文件并查看其中会产生哪些类,那么情况将几乎相同,此时您可能会错过某个文件.
But the situation would be pretty much the same if you tried to include all files and see which classes would come out of it, when there would be a chance that you missed a file.
无论您尝试做什么:尝试不同的方式.我非常怀疑你必须在服务一个请求时实例化所有这些类.如果您必须扫描所有声明的类以查找接口,然后为所有这些类创建一个实例,这对性能不会有很大好处.
Whatever it is what you try to do: Try it differently. I highly doubt you have to instantiate ALL these classes when serving one single request. It would not be very beneficial to the performance if you had to scan ALL declared classes for an interface, and then create an instance for all of them.
提供某种注册方法让应用程序知道您的类.如果你真的必须使用它们,那就这样吧.但是扫描之前运行的任何代码听起来都不对(而且你根本没有解释你在做什么).
Provide some kind of registering method to let the application know about your classes. If you really have to use them all, so be it. But scanning whatever code has been run previously does not sound right (and you didn't explain what you do at all).
相关文章