如何获取子类的所有方法?

时间:2011-12-24 02:08:15

标签: php oop class object

我正在将对象实例编程到其他对象。 现在我需要验证实例化的对象。

我正在使用的代码是正确的,但对象是另一个对象的子代,所以进一步支持父母的方法。

代码:

<?php
class MyParentClass
{
    ...

    $objectName = "subClassExample";
    $obj = new $objectName();
    print_r( get_class_methods( $obj ) );

    ...
}
?>

返回

Array ( [0] => __construct [1] => myMethod )

子类:

<?php
class subClassExample extends parentClass
{

    public function myMethod()
    {
        return null;
    }
}
?>

我需要回复:

Array ( [0] => myMethod )

父类:

<?php
class parentClass
{

    function __construct ()
    {
        return null;
    }
}
?>

我希望我能提供帮助,我真的很感激。 问候!

P.S。:请原谅我的英语不是我的语言,我会讲西班牙语和挪威语Bokmal。

2 个答案:

答案 0 :(得分:2)

您可以使用PHP's Reflection­Docs执行此操作:

class Foo
{
    function foo() {}
}

class Bar extends Foo
{
    function bar() {}
}

function get_class_methodsA($class)
{
    $rc = new ReflectionClass($class);
    $rm = $rc->getMethods(ReflectionMethod::IS_PUBLIC);

    $functions = array();
    foreach($rm as $f)
        $f->class === $class && $functions[] = $f->name;

    return $functions;
}

print_r(get_class_methodsA('Bar'));

输出:

Array
(
    [0] => bar
)

答案 1 :(得分:0)

You may do this check inside a child or a parent class if you need only UNIQUE child's methods:

$cm = get_class_methods($this); //Get all child methods
$pm = get_class_methods(get_parent_class($this)); //Get all parent methods
$ad = array_diff($cm, $pm); //Get the diff

Keep in mind: get_class_methods returns all types of methods (public, protected etc.)