PHP 5 compatible backtrace hack returns calling class from static methods
Here's a working backtrace hack for PHP 5: (thanks for Ren's tip on Joshua Eichorn's blog)
You can make a global function if you like:
PHP Code:
// Find the calling class from within a static method.
function get_calling_class() {
$trace = debug_backtrace();
$lines = file($trace[1]['file']);
$line = $lines[$trace[1]['line'] -1];
preg_match('@[a-z_][a-z0-9_]*(?=::' . $trace[1]['function'] . ')@i', $line, $matches);
return $matches[0];
}
Now you can use it from any static method:
PHP Code:
class MyParent {
public static function parentMethod() {
$callingClass = get_calling_class();
echo "Calling class: $callingClass\n";
}
}
class Kiddo extends MyParent {
}
Kiddo::parentMethod();
// returns "Calling class: Kiddo"