Codeigniter未定义属性,可以';t将模型加载到控制器中


Codeigniter undefined property, can't load model into controller

我正在使用CodeIgniter 3,我在这个网站上看到过类似的问题,并尝试了提供的每一种解决方案,但都无济于事。

我正在尝试使用CodeIgniter通过cli创建一个表。但这导致了一个我似乎无法理解的错误,任何帮助都将不胜感激!

型号:

<?php
class App_model extends CI_Model {
  public function __construct(){
    parent::__construct();
    $this->load->database();
  }
  public function create_table(){
    $this->drop();
    $sql='CREATE TABLE app (
      id int(11) NOT NULL AUTO_INCREMENT,
      text text NOT NULL,
      PRIMARY KEY (id)
    );';
    $this->db->query($sql);
  }
  public function drop(){
    $this->db->query('DROP TABLE app');
  }
}
?>

控制器:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class App extends CI_Controller {
    public function __contruct(){
      parent::__construct();
      $this->load->model('App_model');
    }
    public function test(){
      $this->App_model->create_table();
    }
}
?>

终端:

asergey91:~/workspace $ php index.php App test
A PHP Error was encountered
Severity:    Notice
Message:     Undefined property: App::$App_model
Filename:    /home/ubuntu/workspace/application/controllers/App.php
Line Number: 10
Backtrace:
        File: /home/ubuntu/workspace/application/controllers/App.php
        Line: 10
        Function: _error_handler
        File: /home/ubuntu/workspace/index.php
        Line: 292
        Function: require_once

Fatal error: Call to a member function create_table() on a non-object in /home/ubuntu/workspace/application/controllers/App.php on line 10
Call Stack:
    0.0003     255192   1. {main}() /home/ubuntu/workspace/index.php:0
    0.0010     317824   2. require_once('/home/ubuntu/workspace/system/core/CodeIgniter.php') /home/ubuntu/workspace/index.php:292
    0.0171    1549776   3. call_user_func_array:{/home/ubuntu/workspace/system/core/CodeIgniter.php:514}() /home/ubuntu/workspace/system/core/CodeIgniter.php:514
    0.0171    1550040   4. App->test() /home/ubuntu/workspace/system/core/CodeIgniter.php:514

A PHP Error was encountered
Severity:    Error
Message:     Call to a member function create_table() on a non-object
Filename:    /home/ubuntu/workspace/application/controllers/App.php
Line Number: 10
Backtrace:

正如注释中所说:控制器的文件名必须以大写字母开头。在您的案例中,App_model.php。看见http://codeigniter.com/userguide3/changelog.html

更改了文件命名约定(类文件名现在必须是Ucfirst以及其他所有小写字母(。

因此将app_model.php更改为App_model.php

编辑:

此外,在控制器中,观察大写字母:$this->load->model('app_model')$this->app_model->...。除非在文件名中,否则不要使用任何大写字母。

删除关闭的php标记。

最后,您有一个打字错误function __contruct而不是function __construct()

Codignitor 3中,您需要为文件使用首字母大写,如:

app_model.php

应为:

App_model.php