tags:

views:

59

answers:

2

I'm trying to get a list of methods that were actually defined in a definition for a given class (not just inherited from another class). For example:

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";

I'd like the result to be:

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

Is this possible?

A: 

I haven't tried it, but it looks like you want to use 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";
}

?>

The above example will output:

myclass myfunc1 myfunc2

+3  A: 

You can use Reflection for this:

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

This will actually give you an array of ReflectionMethod objects, but you can easily extrapolate what you need from there. ReflectionMethods provide a getDeclaringClass() function for this, so you can find which functions were declared in which class:

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

This will give:

Array ( [0] => bob )

So, as a final solution, try this:

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;
}
zombat
Works perfectly. Thanks!
B T