PHP 如何获取带有类和命名空间路径的方法名称作为字符串?

Vyt*_*kas 7 php string methods namespaces class

我真的很讨厌写这个问题,因为我是一种“研究人员”,而且,我总能找到我正在寻找的东西……但这让我很烦恼,我在任何地方都找不到答案......所以,它是这样的:

正如标题所说,我需要获取一个带有尾随类和命名空间路径的方法名称作为字符串。我的意思是这样的:"System\Language\Text::loadLanguageCache"。正如我们所知,您可以通过键入 ie: 来获取类名(带有完整的命名空间路径)Text::class,它返回"System\Language\Text",但是有没有办法为方法获取它?类似于:Text::loadLanguageCache::function获取字符串:"System\Language\Text::loadLanguageCache"

编辑:

我想我应该进一步解释这一点......我知道魔法常数,__METHOD__但问题是它在被调用的方法内部工作,我需要这个“在方法之外”。以此为例:

//in System\Helpers
function someFunction()
{ return __METHOD__; }
Run Code Online (Sandbox Code Playgroud)

如果我调用我将获得的函数(假设该方法在System\Helpers类中),那就没问题了- "System\Helpers::someFunction"。但我想要的是这个:

//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"
}
Run Code Online (Sandbox Code Playgroud)

我希望这可以解决我的问题:)

mcu*_*ros 3

您必须使用魔法常量,您可以在 php.net 中的魔法常量中阅读更多信息

__METHOD__
Run Code Online (Sandbox Code Playgroud)

在类之外,您必须使用Reflection,如ReflectionClass文档中所述:

<?php
$class = new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>;
Run Code Online (Sandbox Code Playgroud)

返回:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(9) "getMethod"
  ["class"]=>
  string(15) "ReflectionClass"
}
Run Code Online (Sandbox Code Playgroud)