PHP如何获取带有类和名称空间路径作为字符串的方法名称? [英] PHP How to get a method name with a class and namespace path as a string?
问题描述
我真的很讨厌写这个问题,因为我有点研究人员",而且,我总是能找到我要寻找的东西……但是这个人让我很烦,我找不到答案无处不在...所以,就这样:
I really hate to write this question because I'm kind-of "research guy" and, well, I always find what I'm searching for... But this one bugs me a lot and I can't find the answer anywhere... So, here it goes:
正如标题所述,我需要获取一个方法名称,该方法名称的结尾类和名称空间路径为字符串.我的意思是这样的:"System \ Language \ Text :: loadLanguageCache"
.众所周知,您可以通过键入以下内容来获得一个类名(具有完整的命名空间路径):即 Text :: class
并返回"System \ Language \ Text"
,但是有一种方法可以解决这个问题吗?类似于: Text :: loadLanguageCache :: function
以获取字符串:"System \ Language \ Text :: loadLanguageCache"
?
As the title says I need to get a method name with the trailing class and namespace path as a string. I mean something like this: "System\Language\Text::loadLanguageCache"
.
As we know, you can get a class name (with full namespace path) by typing, i.e.: Text::class
and it returns "System\Language\Text"
, but is there a way to get this for a method? Something like: Text::loadLanguageCache::function
to get string: "System\Language\Text::loadLanguageCache"
?
我想我应该进一步解释...我知道魔术常量 __ METHOD __
,但是问题是它在被调用方法内有效 ,我需要这个方法之外" .以这个为例:
I think I should explain this further... I know about magic constant __METHOD__
but the problem is that it works inside the called method and I need this "outside the method".
Take this as example:
//in System\Helpers
function someFunction()
{ return __METHOD__; }
如果我调用要获取的函数,就可以了(假设方法在 System \ Helpers
类中)-"System \ Helpers :: someFunction" 代码>.但是我想要的是这样:
That's all OK with this if I call the function I'll get (let's assume that method is in System\Helpers
class) - "System\Helpers::someFunction"
. But what I want is this:
//in System\Helpers
function someFunction()
{ //some code... whatever }
// somewhere not in System\Helpers
function otherFunction()
{
$thatFunctionName = Helpers::someFunction::method //That imaginary thing I want
$thatClassName = Helpers::class; //this returns "System\Helpers"
}
我希望这可以使我的问题稍微有所一点:)
I hope this cleared my question a bit :)
推荐答案
You must use the magic constant, you can read more about at Magic constants in php.net
__METHOD__
在课程之外,您必须使用 Reflection ,具体说明请参见 ReflectionClass 文档:
Outside of the class you must use Reflection as is explained at ReflectionClass documentation:
<?php
$class = new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>;
返回:
object(ReflectionMethod)#2 (2) {
["name"]=>
string(9) "getMethod"
["class"]=>
string(15) "ReflectionClass"
}
这篇关于PHP如何获取带有类和名称空间路径作为字符串的方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!