简体   繁体   English

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

[英]Find the class name of the calling function in php

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) (这是针对PHP 5.3)

您可以从debug_backtrace http://php.net/manual/en/function.debug-backtrace.php获取调用者的信息

Full usable solution using exception, but not debug_backtrace, no need to modify any prototype : 使用异常的完整可用解决方案,但不使用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();

One not so good solution is : use __METHOD__ or __FUNCTION__ or __CLASS__ . 一种不太好的解决方案是:使用__METHOD____FUNCTION____CLASS__ and pass it as parameter to function being called. 并将其作为参数传递给要调用的函数。 http://codepad.org/AVG0Taq7 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();

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM