首页 > 解决方案 > 反射调用满足某个属性的类中的函数

问题描述

我有几个实现IInfoProvider. 每个子类都有一个重新实现的函数providesInfoFor(),该函数返回string它可以执行操作的设备类型的名称。每个子类提供不同类型的操作。例如,ABCInfoProvider将声明像 and 之类的函数doThis($device)doThat($device)XYZInfoProvider将声明像doNow($device)and之类的函数doLater($device)。我没有实例化ABCInfoProvideror的任何实例,XYZInfoProvider所以它们没有出现在我的get_declared_classes. 这是一个基于 Laravel 的应用程序,下面是我正在尝试工作的代码片段:

//Works if I uncomment these two lines, which I don't want to do
//$a = new ABCDeviceInfoProvider();
//$a = new XYZDeviceInfoProvider();

//Iterate over each class
foreach (get_declared_classes() as $className) {

    //Check if the class derives from IInfoProvider
    if (in_array(IInfoProvider::class, class_implements($className))) {

        //Create an instance of the class since it derives from IInfoProvider
        $infoProvider = new $className();

        //Check that the IInfoProvider has a specific function on it
        if (method_exists($infoProvider, $action)) {

            //Call the function, this is equivlent to 'new ABCInfoProvider()->doThis($device);'
            $response = $infoProvider->$action($device);

            return response()->json($response);
        } else {
            return response()->json(['error' => 'Action not implemented for device'], 400);
        }
    }
}

所以,问题是,如果我还没有声明我的任何一个实例,我怎样才能让它工作IInfoProviders?有没有另一种方法可以让我在运行时调用一个可能存在也可能不存在的类的函数?

标签: phplaravelreflection

解决方案


推荐阅读