查找定义了类的 PHP 文件(在运行时) [英] Finding the PHP File (at run time) where a Class was Defined
问题描述
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 类的名称,或者一个实例化的对象.我想将它传递给 something(函数、反射类等),它会返回定义类的文件系统路径.
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.
推荐答案
Try ReflectionClass
- ReflectionClass::getFileName — 获取文件名
- 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屋!