2011-05-20 81 views
7

例如PHP获取父类文件路径

的index.php //我知道这个文件是

$class = new childclass(); 
$class->__initComponents(); 

somefile.php //我知道这个文件是

Class childclass extends parentclass { 

} 

someparentfile.php //我不知道这个文件在哪里

Class parentclass { 
    function __initComponents(){ 
    //does something 
    } 
} 

我需要找出someparentfile.php在哪里。

原因:

我调试一些困难的PHP代码是别人写的,我需要找出哪些文件包含定义一个类参数的代码。

我觉得只要一个类的方法调用,这是否一个功能:

$class->__initComponents();//the parameter is defined somewhere in there 

的问题是,这个功能是上面$类的父类“MyClass的”中,我有不知道父类是哪里。

有没有一种方法或一些调试功能,通过它我可以找出这个父类的位置或至少在哪里定义了参数?

p.s. 下载整个应用程序,然后使用文本搜索将是不合理的。

回答

10

您可以使用反射

$object = new ReflectionObject($class); 
$method = $object->getMethod('__initComponents'); 
$declaringClass = $method->getDeclaringClass(); 
$filename = $declaringClass->getFilename(); 

如需进一步信息,什么是可能的反射API,见the manual

然而

,为简单起见,我建议下载源代码和调试它本地。

+0

我知道reflectionobjects,但我不知道他们可以做到这一切。你为我节省了无数小时的调试时间! :D我找到了我正在寻找的方法,但我仍然不知道MyClass在哪里,它看起来像MyClass也是一个扩展类 – 2011-05-20 11:53:59

+0

'$ declaringClass'在我的例子中是类,它实现了方法。 '$ filename'是声明类的文件名。如果你想知道'__initComponents()'在哪里定义,那么它也不在乎,如果'MyClass'也被扩展。如果你认为,你可以使用'ReflectionClass :: getParentClass()'获得父类,这对你有帮助。 – KingCrunch 2011-05-20 12:15:07

+0

它帮助我找到我需要的类(最外层的父类),而不是我认为我需要的类(直接父类“MyClass”),现在使用getParentClass,我甚至找到了“MyClass”(我不需要,但很有趣),所以我修复了一大堆bug,现在一切正常:) – 2011-05-21 14:37:00

3
$object = new ReflectionObject($this); // Replace $this with object of any class. 

    echo 'Parent Class Name: <br>'; 
    echo $object->getParentClass()->getName(); 

    echo '<br>Parent Class Location: <br>'; 
    echo $object->getParentClass()->getFileName();