传递给App \ Models \ Model :: __ construct()必须是一个实例

时间:2018-05-28 18:11:38

标签: php

我试图让主模型出现这个错误:

致命错误:未捕获TypeError:传递给App \ Models \ Model :: __ construct()的参数1必须是App \ Models \ Database的实例,App \ Database的实例,在C:\ xampp \ htdocs \中调用第14行的Work \ AppDarbNajah \ App \ Controllers \ ArticlesController.php,在C:\ xampp \ htdocs \ Work \ AppDarbNajah \ App \ Models \ Model.php中定义:9堆栈跟踪:#0 C:\ xampp \ htdocs \ Work \ AppDarbNajah \ App \ Controllers \ ArticlesController.php(14):App \ Models \ Model-> __ construct(Object(App \ Database))#1 C:\ xampp \ htdocs \ Work \ AppDarbNajah \ Public \ index.php( 22):在第9行的C:\ xampp \ htdocs \ Work \ AppDarbNajah \ App \ Models \ Model.php中抛出的App \ Controllers \ ArticlesController-> loadArticles()#2 {main}

我的代码是 1-模型

<?php
namespace App\Models;


class Model{
  protected $db;
  protected $table;

  public function __construct(Database $db){
     $this->db = $db;
  }
  public function query($statement, $attributes= null){
     return $this->db->query($statement);
  }
}   

2- ArticlesController

<?php
namespace App\Controllers;


use App\Models\ArticlesModel;

class ArticlesController{
     public function loadArticles() {

     $app = new \App();
     $art_table = new ArticlesModel($app->getDb());
     return $art_table->load();


  }
}

1 个答案:

答案 0 :(得分:0)

由于class Model位于namespace App\Models;,因此对Database的{​​相对}引用总共为App\Models\Database

您现在可以将参考设为绝对值:

__construct(\App\Database $db) { ...

或将use App\Database;放在命名空间之后。

More info can be found in the Docs