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?
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.
You just creating the Log
object inside of Foo
, therefore your get_called_class()
call will always result in Log
. You need to make Foo
inherit Log
if you want that kind of behavior. For example:
<?php
class Log {
public function msg($message) {
// Tell which class/function is calling this function here
$class = get_called_class();
echo 'Your message was: "'.$message.'" from class: "'.$class.'"';
}
}
class Foo extends Log {
public function doSomething() {
$this->msg( 'Hello World!' );
}
}
$foo = new Foo();
$foo->doSomething();
Outputs:
Your message was: "Hello World!" from class: "Foo"