查找定义了类的PHP文件(在运行时) [英] Finding the PHP File (at run time) where a Class was Defined

查看:119
本文介绍了查找定义了类的PHP文件(在运行时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中有没有反射/自省/魔法,它会让你找到定义了特定类(或函数)的PHP文件?

Is there any reflection/introspection/magic in PHP that will let you find the PHP file where a particular class (or function) was defined?

换句话说, ,我有一个PHP类的名称,或实例化的对象。我想将此传递给某些(函数,Reflection类等),它将返回定义类的文件系统路径。

In other words, I have the name of a PHP class, or an instantiated object. I want to pass this to something (function, Reflection class, etc.) that would return the file system path where the class was defined.

/path/to/class/definition.php

实现我可以使用( get_included_files())获得所有已经包括的文件的列表,然后手动解析它们,但这是一个很大的文件系统访问单次尝试。

I realize I could use (get_included_files()) to get a list of all the files that have been included so far and then parse them all manually, but that's a lot of file system access for a single attempt.

我也意识到我可以在我们的__autoload机制中写一些额外的代码来缓存这些信息。但是,修改现有的__autoload在我考虑的情况下是没有限制的。

I also realize I could write some additional code in our __autoload mechanism that caches this information somewhere. However, modifying the existing __autoload is off limits in the situation I have in mind.

听到可以做到这一点的扩展很有趣,但我最终想要的东西


Hearing about extensions that can do this would be interesting, but I'd ultimately like something that can run on a "stock" install.

推荐答案

试用

  • ReflectionClass::getFileName — Gets a filename

示例:

class Foo {}
$reflector = new ReflectionClass('Foo');
echo $reflector->getFileName();

当文件名不能为空时,将返回 false 例如在本地类。

This will return false when the filename cannot be found, e.g. on native classes.

这篇关于查找定义了类的PHP文件(在运行时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆