Php 在类中获取父函数

Php 在类中获取父函数,php,Php,有可能吗?如果是这样,怎么办?! 我知道我可以传递一个参数,但我希望它是动态的 <?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

有可能吗?如果是这样,怎么办?! 我知道我可以传递一个参数,但我希望它是动态的

<?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
}

?>

如果您想获取调用
my_类的构造函数的函数名,可以使用PHP,如下所述:


坦率地说,这似乎是一个非常糟糕的设计选择,但是可以使用PHP内置的debug\u backtrace
函数使用调用堆栈内省来实现这一点。以下示例来自:

如果您很聪明,您可以在回溯中使用函数的函数名来调用它,例如,
debug_backtrace()[1]['function']()
,但是只有在您当前正在执行的范围中定义函数时,这才起作用。有关从字符串按函数名调用函数的详细信息,请参见

然而,在我看来,你没有理由在一个精心设计的程序中这样做。也许您应该考虑改用对象和对象引用。

您也可以使用(即使可能有更好的设计):

那么就:

function some_random_function() {
  // Do something
  $object = new my_class('some_random_function');

  print $object->parent(); // returns: some_random_function
}

“家长”是指
my_class
扩展的类吗?因为这很简单:
parent::get\u parent\u函数
。但听起来你在追求不同的东西…看起来设计很糟糕。我可以问一下,您为什么要这样做吗?@sdleihsirhc他正在尝试获取创建对象的函数的引用。我正在尝试创建一个简单的运行时缓存类,该类使用函数名作为键。我认为这是
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"
  }
}
public function __construct($functionname = NULL) {
    $this->parent = $functionname; 
}
function some_random_function() {
  // Do something
  $object = new my_class('some_random_function');

  print $object->parent(); // returns: some_random_function
}