以某种方式可能吗?如果是这样的话怎么样?!我知道我可以通过一个参数,但我希望它是动态的!
<?php
class my_class {
protected $parent = NULL;
public function __construct() {
// now i'd like to get the name of the function where this class has been called
$this->parent = get_parent_function();
}
public function parent() {
return $this->parent;
}
}
function some_random_function() {
// Do something
$object = new my_class();
print $object->parent(); // returns: some_random_function
}
?>
Run Code Online (Sandbox Code Playgroud)
提前致谢!
坦率地说,这似乎是一个非常糟糕的设计选择,但是使用PHP内置debug_backtrace函数使用调用堆栈内省可以做到这一点.以下示例来自php文档debug_backtrace:
<?php
// filename: /tmp/a.php
function a_test($str)
{
echo "\nHi: $str";
var_dump(debug_backtrace());
}
a_test('friend');
?>
<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>
Run Code Online (Sandbox Code Playgroud)
如果执行b.php,输出可能如下所示:
Hi: friend
array(2) {
[0]=>
array(4) {
["file"] => string(10) "/tmp/a.php"
["line"] => int(10)
["function"] => string(6) "a_test"
["args"]=>
array(1) {
[0] => &string(6) "friend"
}
}
[1]=>
array(4) {
["file"] => string(10) "/tmp/b.php"
["line"] => int(2)
["args"] =>
array(1) {
[0] => string(10) "/tmp/a.php"
}
["function"] => string(12) "include_once"
}
}
Run Code Online (Sandbox Code Playgroud)
如果你是聪明的,你可以使用该函数的函数名在回溯称呼它,比如debug_backtrace()[1]['function'](),但是如果该功能在您当前正在执行的范围定义这只会工作,见可变功能的PHP文件的有关通过字符串中的名称调用函数的更多信息.
但是,在我看来,你没有理由在精心设计的程序中这样做.也许您应该考虑使用对象和对象的引用.