我想在循环中实例化类,我尝试这样做:
<?php
use App\Caves_demographic_info;
use App\Caves_current_uses;
use App\Caves_flora_outside;
public function get_page4_contd_data($id) {
$tables = [
'Caves_demographic_info', 'Caves_current_uses', 'Caves_flora_outside',
];
for($index = 0; $index < count($tables); $index++) {
${$tables[$index]."_model"} = new $tables[$index];
}
}
?>
它会产生错误“找不到类{class_name}”,是否可以在循环内执行该操作?
答案 0 :(得分:1)
您的方法似乎正确,可以尝试(使用名称空间)
$className = 'App\' . $tables[$index];
$class = new $className;
在您的示例中是这样的:
$tables = [
'App\Caves_demographic_info',
'App\Caves_current_uses',
'App\Caves_flora_outside',
];
for($index = 0; $index < count($tables); $index++) {
${$tables[$index]."_model"} = new $tables[$index];
}