查找定义了类的 PHP 文件(在运行时)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2420066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:24:15  来源:igfitidea点击:

Finding the PHP File (at run time) where a Class was Defined

phpreflectionclass

提问by Alan Storm

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 中是否有任何反射/内省/魔法可以让您找到定义特定类(或函数)的 PHP 文件?

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.

换句话说,我有一个 PHP 类的名称,或者一个实例化的对象。我想把它传递给一些东西(函数、反射类等),它会返回定义类的文件系统路径。

/path/to/class/definition.php

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.

我意识到我可以使用 (get_included_files())来获取到目前为止包含的所有文件的列表,然后手动解析它们,但一次尝试需要大量的文件系统访问。

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.

我也意识到我可以在我们的 __autoload 机制中编写一些额外的代码,将这些信息缓存在某处。但是,在我想到的情况下,修改现有的 __autoload 是禁止的。

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

听说可以做到这一点的扩展会很有趣,但我最终还是喜欢可以在“库存”安装上运行的东西。

回答by Gordon

Try ReflectionClass

尝试 ReflectionClass

Example:

例子:

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

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

这将false在找不到文件名时返回,例如在本机类上。

回答by Jevin

For ReflectionClass in a namespacedfile, add a prefix "\" to make it global as following:

对于命名空间文件中的ReflectionClass ,添加前缀“\”使其成为全局的,如下所示:

$reflector = new \ReflectionClass('FOO');

$reflector = new \ReflectionClass('FOO');

Or else, it will generate an error said ReflectionClass in a namespace not defined. I didn't have rights to make comment for above answer, so I write this as a supplement answer.

否则,它会在未定义的命名空间中生成一个错误,表示 ReflectionClass。 我无权对上述答案发表评论,因此我将其写为补充答案。

回答by Seaux

if you had an includes folder, you could run a shell script command to "grep" for "class $className" by doing: $filename = ``grep -r "class $className" $includesFolder/*\and it would return which file it was in. Other than that, i don't think there is any magic function for PHP to do it for ya.

如果你有一个包含文件夹,你可以运行一个 shell 脚本命令来为“class $className”“grep”执行以下操作:$filename = ``grep -r "class $className" $includesFolder/*\它会返回它所在的文件。除此之外,我认为没有任何魔法PHP 为你做这件事的函数。