我有一些代码,用户可以在其中通过数据库设置任意数量的数组元素。我使用的是基于键名的鸭式输入功能,但并非所有键名都是要调用的对象,而且我不能保证键的顺序可以是静态的。代码类似于此:
$arr = get_arr_from_db();
foreach($arr as $key => $val){
if($obj = new $key){
unset($arr[$key]);
$obj->give_data($arr);
break;
}
}
$obj->quack();
上面的代码不起作用,因为
$obj = new $key
将死亡。有什么办法可以防止上述循环在对象创建失败后消失?
最佳答案
您可以在尝试实例化之前使用class_exists()
,并且try/catch块将在无法实例化时捕获任何错误。
foreach($arr as $key => $val){
if(class_exists($key)){
try {
if($obj = new $key){
unset($arr[$key]);
if(method_exists($obj, 'give_data'){
$obj->give_data($arr);
}
break;
}
} catch(Exception $e) {
// do something with the exception
}
}
}
关于php - PHP-错误处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14048115/