douli1872
2014-08-02 18:23
浏览 93
已采纳

获取在PHP中调用函数的类的名称

I have two separate classes where one of them is a logging class. I would like to be able to tell which class is calling the log class functions without passing any parameters.

<?php
class Log {
    public function general($message) {
        // Tell which class/function is calling this function here
        $class = get_called_class();

        echo 'Your message was: "'.$message.'" from class: "'.$class.'"';
    }
}

class foo {
    public function log_something() {
        $Log = new Log();
        $Log->general('Hello, world!');
    }
}

$foo = new Foo();
$foo->log_something();

?>

The output I would like is: Your message was "Hello, world!" from class "foo"

However, the message I'm getting is: Your message was "Hello, world!" from class "Log"

Am I missing something, or doing something wrong?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • douchen5971 2014-08-05 13:21
    最佳回答

    I was able to figure out the answer to my problem by using debug_backtrace()

    <?php
    class Log {
        private function get_call_class() {
            $backtrace = debug_backtrace();
    
            $classes = array();
            foreach ($backtrace as $item) {
                if ($item['class'] != '' && $item['class'] != 'Log') $classes[] = $item['class'];
            }
            return $classes[0];
        }
    
        public function general($message) {
            // Tell which class/function is calling this function here
            $class = $this->get_call_class();
    
            echo 'Your message was: "'.$message.'" from class: "'.$class.'"';
        }
    }
    
    
    class foo {
        public function log_something() {
            $Log = new Log();
            $Log->general('Hello, world!');
        }
    }
    
    $foo = new Foo();
    $foo->log_something();
    
    ?>
    

    Explanation: The Log->get_call_class() function gets information from debug_backtrace() and loops through it to find the classes that don't have the name of 'Log' or blank names then returns the first result, which is the one I was looking for.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题