PHP: How to get all classes when using autoloader(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).
这篇关于PHP:使用自动加载器时如何获取所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP:使用自动加载器时如何获取所有类
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Laravel 仓库 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01