【问题标题】:How to get all the methods of a subclass?如何获取子类的所有方法?
【发布时间】:2011-12-24 02:08:14
【问题描述】:

我正在为其他对象编写一个对象实例。 现在我需要验证一个实例化的对象。

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

代码:

<?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。

【问题讨论】:

  • 什么是$objectName?它是哪个物体?
  • $objectName 是对象名称...例如:$objectName = 'subClassExample';

标签: php oop class object


【解决方案1】:

您可以使用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
)

【讨论】:

  • 太好了,谢谢!它证明了,但只有文档和像我一样看到(:-})
【解决方案2】:

如果您只需要 UNIQUE 子类的方法,您可以在子类或父类中执行此检查:

$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

请记住:get_class_methods 返回所有类型的方法(公共、受保护等)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 2012-12-26
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    相关资源
    最近更新 更多