代码之家  ›  专栏  ›  技术社区  ›  B T

如何获得PHP类中最初*定义*的方法列表?

  •  0
  • B T  · 技术社区  · 15 年前

    我试图得到一个方法列表,这些方法实际上是在一个给定类的定义中定义的(不仅仅是从另一个类继承的)。例如:

    class A
    {   function bob()
        {
        }
    }
    class B extends A
    {   function rainbrew()
        {
        }
    
    }
    class C extends B
    {   function bob()
        {
        }
    }
    
    echo print_r(get_defined_class_methods("A"), true)."<br>\n";
    echo print_r(get_defined_class_methods("B"), true)."<br>\n";
    echo print_r(get_defined_class_methods("C"), true)."<br>\n";
    

    我希望结果是:

    array([0]=>bob)
    array([0]=>rainbrew)
    array([0]=>bob)
    

    这有可能吗?

    2 回复  |  直到 15 年前
        1
  •  4
  •   zombat    15 年前

    你可以使用 Reflection 为此:

    $reflectA = new ReflectionClass('A');
    print_r($reflectA->getMethods());
    

    这实际上会给你一个ReflectionMethod对象数组,但是你可以很容易地从那里推断出你需要什么。反射方法提供 getDeclaringClass() 函数,这样您就可以找到在哪个类中声明了哪些函数:

    $reflectC = new ReflectionClass('C');
    $methods = $reflectC->getMethods();
    $classOnlyMethods = array();
    foreach($methods as $m) {
        if ($m->getDeclaringClass()->name == 'C') {
            $classOnlyMethods[] = $m->name;
        }
    }
    print_r($classOnlyMethods);
    

    这将给予:

    Array ( [0] => bob )
    

    因此,作为最终解决方案,请尝试以下方法:

    function get_defined_class_methods($className)
    {
        $reflect = new ReflectionClass($className);
        $methods = $reflect->getMethods();
        $classOnlyMethods = array();
        foreach($methods as $m) {
            if ($m->getDeclaringClass()->name == $className) {
                $classOnlyMethods[] = $m->name;
            }
        }
        return $classOnlyMethods;
    }
    
        2
  •  -1
  •   sissonb    15 年前

    我没试过,但你好像想用 get_class_methods

    <?php
    
    class myclass {
        // constructor
        function myclass()
        {
            return(true);
        }
    
        // method 1
        function myfunc1()
        {
            return(true);
        }
    
        // method 2
        function myfunc2()
        {
            return(true);
        }
    }
    
    $class_methods = get_class_methods('myclass');
    // or
    $class_methods = get_class_methods(new myclass());
    
    foreach ($class_methods as $method_name) {
        echo "$method_name\n";
    }
    
    ?>
    

    上面的示例将输出:

    MyClass MyFunc1 MyFunc2