php - 反射调用满足某个属性的类中的函数
问题描述
我有几个实现IInfoProvider
. 每个子类都有一个重新实现的函数providesInfoFor()
,该函数返回string
它可以执行操作的设备类型的名称。每个子类提供不同类型的操作。例如,ABCInfoProvider
将声明像 and 之类的函数doThis($device)
,doThat($device)
而XYZInfoProvider
将声明像doNow($device)
and之类的函数doLater($device)
。我没有实例化ABCInfoProvider
or的任何实例,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
?有没有另一种方法可以让我在运行时调用一个可能存在也可能不存在的类的函数?
解决方案
推荐阅读
- babeljs - 为什么 Babel 会抛出 Unknown option: ... Children?
- scala - 如何根据另一个数据框中的数据填充数据框值
- javascript - console.log() 在遇到空白时截断
- string - 用于机器学习或深度学习的基于字符串的数据的数据转换
- c# - Linq select 语句在输出控制台中打印 project.class 名称作为结果
- javascript - 如何插入可以将用户输入作为文本的选项
- java - JavaFX Canvas 不显示图纸
- ios - 使用 Mapbox Direction API 生成路线时避免坐标
- algorithm - 对数复杂度的误解
- python - Tkinter - 使用多个键绑定