Find the class name of the calling function in php

与世无争的帅哥 提交于 2020-01-03 03:40:30

问题


Lets say I have:

    class Zebra{
        public static function action(){
            print 'I was called from the '.get_class().' class'; // How do I get water here?
        }
    }

    class Water{
        public static function drink(){
            Zebra::action();
        }
    }

Water::drink();

How do I get "water" from the zebra class?

(This is for php 5.3)


回答1:


One not so good solution is : use __METHOD__ or __FUNCTION__ or __CLASS__ . and pass it as parameter to function being called. http://codepad.org/AVG0Taq7

<?php

  class Zebra{
        public static function action($source){
            print 'I was called from the '.$source.' class'; // How do I get water here?
        }
    }

    class Water{
        public static function drink(){
            Zebra::action(__CLASS__);
        }
    }

Water::drink();

?>



回答2:


You can get the caller's info from debug_backtrace http://php.net/manual/en/function.debug-backtrace.php




回答3:


Full usable solution using exception, but not debug_backtrace, no need to modify any prototype :

function getRealCallClass($functionName)
{
  try
   {
     throw new exception();
   }
  catch(exception $e)
   {
     $trace = $e->getTrace();
     $bInfunction = false;
     foreach($trace as $trace_piece)
      {
          if ($trace_piece['function'] == $functionName)
           {
             if (!$bInfunction)
              $bInfunction = true;
           }
          elseif($bInfunction) //found !!!
           {
             return $trace_piece['class'];
           }
      }
   }
}

class Zebra{
        public static function action(){
        print 'I was called from the '.getRealCallClass(__FUNCTION__).' class'; 
    }
}

class Water{
    public static function drink(){
        Zebra::action();
    }
}

Water::drink();


来源:https://stackoverflow.com/questions/7427670/find-the-class-name-of-the-calling-function-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!