2014-05-07 27 views
0

我有一系列使用大量方法重載的繼承類,並且我需要一種方法來找出當它調用特定方法時正在使用哪個類。如何從調用方法獲取類名?

簡單的例子:

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')); 
+0

這不只是這一個修改版本: http://stackoverflow.com/questions/10493720/how-to-get-the-protected-stastic-主要作用範圍內的子範圍/ 10494032#10494032 很明顯,您不需要在構建中使用回顯,並且「get_table_name_protected」將更改爲「_run」。但是......看起來像是你想要的,除非我搞砸了一些東西。 –

回答

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'; 
?> 
012的上面的代碼個

結果:

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()); 
} 
+0

唯一的問題是,我不知道哪個類的函數被調用,否則我會知道該類已經。 –

+0

@FrancisLewis更新 –

+0

@FrancisLewis再次更新。例子來自資源。如果你需要,你可以研究得更好。現在要睡覺!再見:)祝你工作順利。 –