Reputation: 123
I want to instantiate class inside the loop, I've tried doing this:
<?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];
}
}
?>
It produces the error 'Class {class_name} not found', Is it possible to do that inside the loop?
Upvotes: 0
Views: 73
Reputation: 12857
Your approach seems right, can you try (with namespace)
$className = 'App\' . $tables[$index];
$class = new $className;
So something like this in your example:
$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];
}
Upvotes: 1