The answers here don't actually suggest any reliable way to achieve this... while they do work, they are unreliable in the sense that they're only returning classes that have been loaded, which is not what anyone really wants and is redundant to instanceof
in the scenarios that these methods are potentially useful for.
get_declared_classes()
Returns an array of the names of the declared classes in the current script.
The keyword here is current script
, this function will not return classes that have not been loaded yet.
interface_exists
Similar to the above, this method will not know if an interface exists, if the interface has not been loaded yet.
It will also autoload the interface (note the second parameter of interface_exists
)
class_implements
Similar to above, this will also autoload your files regardless of your intention to use them.
So, how can I reliably retrieve this information, in an efficient way...
Simply put, construct a manifest with all this information and store it in cache.
Manifests help to cache information which is too expensive to generate on each request. Some manifests generate maps, e.g. class names to filesystem locations. Others store aggregate information like nested configuration graphs.
Here is a great example of a manifest being constructed in an MVC which serves purely to address the issues in the points above.
There is quite a bit of code to consider in implementing a class manifest accurately, and the complete picture would be a little difficult to post in this answer, however here are a few reference points to get you started:
- ClassManifest
- ClassManifestVisitor
The implementation above uses the nikic/php-parser
package, rather than directly using reflection.