PHP:使用自动加载器时如何获取所有类

PHP: How to get all classes when using autoloader(PHP:使用自动加载器时如何获取所有类)
本文介绍了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:使用自动加载器时如何获取所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)