如何在 PHP 中的函数中获取函数名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1006248/
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 00:36:50  来源:igfitidea点击:

How do I get the function name inside a function in PHP?

phpfunction

提问by omg

Is it possible?

是否可以?

function test()
{
  echo "function name is test";
}

回答by Silfverstrom

The accurate way is to use the __FUNCTION__predefined magic constant.

准确的方法是使用__FUNCTION__预定义的魔法常数

Example:

例子:

class Test {
    function MethodA(){
        echo __FUNCTION__;
    }
}

Result: MethodA.

结果:MethodA

回答by PatrikAkerstrand

You can use the magic constants__METHOD__(includes the class name) or __FUNCTION__(just function name) depending on if it's a method or a function... =)

您可以使用魔术常量__METHOD__(包括类名)或__FUNCTION__(只是函数名),具体取决于它是方法还是函数...... =)

回答by Kevin Newman

If you are using PHP 5 you can try this:

如果您使用的是 PHP 5,您可以试试这个:

function a() {
    $trace = debug_backtrace();
    echo $trace[0]["function"];
}

回答by Snehal K

<?php

  class Test {
     function MethodA(){
         echo __FUNCTION__ ;
     }
 }
 $test = new Test;
 echo $test->MethodA();
?>

Result: "MethodA";

结果:“方法A”;