我有两个单独的类,其中一个是日志记录类。我希望能够告诉哪个类在不传递任何参数的情况下调用日志类函数。
<?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();
?>
我想要的输出是:Your message was "Hello, world!" from class "foo"
然而,我得到的信息是:
Your message was "Hello, world!" from class "Log"
我错过了什么,或做错了什么?
答案 0 :(得分:0)
您只需在Log
内创建Foo
对象,因此get_called_class()
来电将始终生成Log
。如果您想要这种行为,则需要Foo
继承Log
。例如:
<?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();
输出:
Your message was: "Hello World!" from class: "Foo"
答案 1 :(得分:0)
我能够使用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();
?>
说明:Log->get_call_class()
函数从debug_backtrace()
获取信息并循环显示该信息,以查找不具有&#39; Log&#39;或者空白名称然后返回第一个结果,这是我正在寻找的结果。