代码之家  ›  专栏  ›  技术社区  ›  Jiel

如何在循环中实例化类(从数组)

  •  0
  • Jiel  · 技术社区  · 7 年前

    <?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{Class\u name}notfound',是否可以在循环中这样做?

    1 回复  |  直到 7 年前
        1
  •  1
  •   senty    7 年前

    你的方法似乎是对的,你能试试吗(用名称空间)

    $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];
    }
    
    推荐文章