在php中找到调用函数的类名

时间:2011-09-15 08:07:08

标签: php static-methods

让我说我有:

    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();

如何从斑马班获得“水”?

(这是针对php 5.3)

3 个答案:

答案 0 :(得分:3)

您可以从debug_backtrace http://php.net/manual/en/function.debug-backtrace.php

获取来电者的信息

答案 1 :(得分:1)

一个不太好的解决方案是: 使用__METHOD____FUNCTION____CLASS__。 并将其作为参数传递给被调用的函数。 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 :(得分:1)

完全可用的解决方案,使用异常,但不是debug_backtrace,无需修改任何原型:

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();