PHP, parse all classes of a specific namespace, and list all methods of theses classes

I have some classes in a specific directory (by example src/faa/foo) and all theses class have the same namespace (App\faa\foo).

I'm looking to find a proper way for list all methods of theses classes from a php script.

I want do something like this :

// list all class of this specific directory
$classes = get_all_class_by_directory_location('src/faa/foo');
// or
$classes = get_all_class_by_namespace('App\foo\faa');
    // but that means I must include theses classes to my script isn't it ? I think it's an ugly way because I only need print methods name, I don't need use them in this script 

foreach($classes as $class){
    print(get_methods($class));
}

What is the best approach for do what I want ? Does it exist a maintained community php package for do that ?

My project follow the psr-4 convention, maybe this information is usefull..

1 answer

  • answered 2018-10-17 07:56 Alexander De Sousa

    <?php
    
    foreach (glob('src/faa/foo/*.php') as $file)
    {
        require_once $file;
    
        // get the file name of the current file without the extension
        // which is essentially the class name
        $class = basename($file, '.php');
    
        if (class_exists($class))
        {
            $obj = new $class;
            foreach(get_class_methods($obj) as $method)
            {
              echo $method . '\n';
            }
        }
    }
    

    Taken from: Create instances of all classes in a directory with PHP then added get_class_methods usage.