Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...