开发者

Get parent function within class

开发者 https://www.devze.com 2023-03-06 06:03 出处:网络
is following somehow possible? And if so how?! I know i could pass a parameter but I\'d like it to be dynamic!

is following somehow possible? And if so how?! I know i could pass a parameter but I'd like it to be dynamic!

<?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()开发者_如何学C;

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

?>

Thanks in advance!


Frankly this seems like a pretty bad design choice, however it would be possible to do this using call stack introspection using the PHP builtin debug_backtrace function. The following example is from the php documentation for 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';
?>

If b.php is executed, the output could look like this:

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

If you were clever you could use the function name of the function in the backtrace to call it, e.g. debug_backtrace()[1]['function'](), but this will only work if the function is defined in the scope that you are currently executing in. See the php documentation on variable functions for more info on calling functions by their name from a string.

In my opinion, though, there should be no reason for you to do this in a well designed program. Perhaps you should think about using objects and references to objects instead.


You could also use (even if there probably are better designs):

public function __construct($functionname = NULL) {
    $this->parent = $functionname; 
}

Then just:

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

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


If you want to get the name of the function that called the constructor of my_class, you can use PHP's debug_backtrace as describe here:

How to get name of calling function/method in PHP?

0

精彩评论

暂无评论...
验证码 换一张
取 消