如何从被调用的方法获取类名?

时间:2014-05-07 22:37:39

标签: php oop

我有一系列使用大量方法重载的继承类,我需要一种方法来找出在调用特定方法时正在使用哪个类。

简单的例子:

class child extends parent
    public function _process()
    {
        $this->_otherrun();
    }

    public function _run()    

class parent extends grandparent
    public function _run()
    public function _otherrun()
    {
        // I need to find out which class the version of _run is called in
        $this->_run();
    }

这个例子与我正在浏览的内容相比非常简单,所以我需要一种方法来查看处理哪个类function _run。这是否可能?

这样的事情:

get_class(array($this, 'run'));

1 个答案:

答案 0 :(得分:0)

您可以使用get_called_class()功能或debug_backtrace()功能:

get_called_class()示例:

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

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';
?>

上述代码的结果:

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

另外,使用搜索。结果之一:Find out which class called a method in another class

更新(评论):使用debug_backtrace()功能。

在你的情况下:

class parent extends grandparent
public function _run()
public function _otherrun()
{
    // I need to find out which class the version of _run is called in
    $this->_run();
    var_dump(debug_backtrace());
}
相关问题