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条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办