Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to get a list of classes that implement certain interface?

Tags:

oop

php

class

I've got an interface

interface IModule {
    public function Install();
}

and some classes that implement this interface

class Module1 implements IModule {
    public function Install() {
        return true;
    }
}

class Module2 implements IModule {
    public function Install() {
        return true;
    }
}

...

class ModuleN implements IModule {
    public function Install() {
        return true;
    }
}

How to get a list of all classes that implement this interface? I'd like to get this list with PHP.

like image 792
foreline Avatar asked Oct 22 '10 03:10

foreline


3 Answers

You dont need Reflection for this. You can simply use

  • class_implements — Return the interfaces which are implemented by the given class

Usage

in_array('InterfaceName', class_implements('className'));

Example 1 - Echo all classes implementing the Iterator Interface

foreach (get_declared_classes() as $className) {
    if (in_array('Iterator', class_implements($className))) {
        echo $className, PHP_EOL;
    }
}

Example 2 - Return array of all classes implementing the Iterator Interface

print_r(
    array_filter(
        get_declared_classes(), 
        function ($className) {
            return in_array('Iterator', class_implements($className));
        }
    )
);

The second example requires PHP5.3 due to the callback being an anonymous function.

like image 63
Gordon Avatar answered Nov 01 '22 07:11

Gordon


You can use PHP's ReflectionClass::implementsInterface and get_declared_classes functions to accomplish this:

$classes = get_declared_classes();
$implementsIModule = array();
foreach($classes as $klass) {
   $reflect = new ReflectionClass($klass);
   if($reflect->implementsInterface('IModule')) 
      $implementsIModule[] = $klass;
}
like image 31
Jacob Relkin Avatar answered Nov 01 '22 06:11

Jacob Relkin


Generic solution:

function getImplementingClasses( $interfaceName ) {
    return array_filter(
        get_declared_classes(),
        function( $className ) use ( $interfaceName ) {
            return in_array( $interfaceName, class_implements( $className ) );
        }
    );
}
like image 13
Jeroen De Dauw Avatar answered Nov 01 '22 07:11

Jeroen De Dauw