简体   繁体   中英

PHP - Getting the class, which has called method

I would like to generate an log file. Therefor I have created a static class called log with an method called write:

class log {  
public static function write($info) {  
// file writing  
}
}

In this function i would like to know from which class the method write is called (automatically):

log::write("Testinformation");

I have already tried with: get_called_class - but this gives me only "log" instead of the "real" called class...

Is there any way to automatically retrieve the called class?

You can't retrieve the class that called it.

use something like:

define("log_tag", "myclass")

at the start of the file, and through out the rest of the file call:

log::write(log_tag, "testinformation");`
$offset = 1;
$backtrace = debug_backtrace();
$caller = array();
if(isset($backtrace[$offset])) {
    $backtrace = $backtrace[$offset];
    if(isset($backtrace['class'])) {
        $caller['class'] = $backtrace['class'];
    }
    if(isset($backtrace['function'])) {
        $caller['function'] = $backtrace['function'];
    }

}

No you have info about calling class and method or function. You can also use function I wrote long time ago

<?php
function getCaller($offset = 0) {
    $baseOffset = 2;
    $offset += $baseOffset;
    $backtrace = debug_backtrace();
    $caller = array();
    if(isset($backtrace[$offset])) {
        $backtrace = $backtrace[$offset];
        if(isset($backtrace['class'])) {
            $caller['class'] = $backtrace['class'];
        }
        if(isset($backtrace['function'])) {
            $caller['function'] = $backtrace['function'];
        }

    }
    return $caller;
}
?>

I think it would be easier to add the class name at the call of the method :

class Foo 
{
    public function bar()
    {
        // do something ... 
        log::write(get_called_class().': blablabla...');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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