代码之家  ›  专栏  ›  技术社区  ›  cwallenpoole

列出给定类的所有方法,不包括PHP中父类的方法

  •  10
  • cwallenpoole  · 技术社区  · 15 年前

    我正在为PHP构建一个单元测试框架,我很想知道是否有一种方法可以获得一个对象列表,其中包含 排除

    class Foo
    {
    
        public function doSomethingFooey()
        {
            echo 'HELLO THERE!';
        }
    }
    
    class Bar extends Foo
    {
        public function goToTheBar()
        {
            // DRINK!
        }
    }
    

    我想要一个函数,给定参数 new Bar() 返回:

    array( 'goToTheBar' );
    

    没有 需要实例化一个Foo实例(这意味着 get_class_methods 不起作用)。

    4 回复  |  直到 13 年前
        1
  •  30
  •   Lukman    15 年前

    使用 ReflectionClass ,例如:

    $f = new ReflectionClass('Bar');
    $methods = array();
    foreach ($f->getMethods() as $m) {
        if ($m->class == 'Bar') {
            $methods[] = $m->name;
        }
    }
    print_r($methods);
    
        2
  •  5
  •   Community CDub    8 年前

    你可以用 get_class_methods() 在不实例化类的情况下:

    $class\u名称 -类名

    $bar_methods = array_diff(get_class_methods('Bar'), get_class_methods('Foo'));
    

    假设父类中没有重复的方法。尽管如此, Lukman's answer

        3
  •  2
  •   Tyler Carter    15 年前
    $class_methods = get_class_methods('Bar');
    

    From the PHP Documenation

    这将不会实例化该类,并允许您获取所有类方法的数组。

    我不能完全肯定这不会返回父类方法,但是 get_class_methods


    顺便说一句,如果你输入 new Bar() ,它将创建一个新的Foo实例,因为Bar扩展了Foo。不能实例化Foo的唯一方法是静态引用它。因此,你的请求:

    I want a function which will, given the parameter new Bar() return:
    

    没有可能的解决办法。如果你给

        4
  •  0
  •   Osama Sheikh    6 年前

    对于任何想知道如何检查特定方法是否属于指定类或其父类的人,您可以通过获取其类名,然后将其与实际类名进行比较,如下面所示。

    $reflection = new \ReflectionMethod($classInstance, 'method_name_here');
    if($reflection->class == MyClass::class)
    echo "Method belongs to MyClass";
    else
    echo "Method belongs to Parent classes of MyClass";