You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter报错:Undefined property: Test_controller::$testFunction

解决CodeIgniter中"Undefined property: Test_controller::$testFunction"错误

我帮你梳理下问题所在,这是CodeIgniter新手常遇到的模型调用误区,咱们一步步来修正:

错误根源拆解

  • 模型实例名称不匹配:当你执行$this->load->model('Test_model');时,CodeIgniter默认会把模型实例化为小写的类名,也就是$this->test_model,而不是你代码里写的$this->Test_model。
  • 方法调用误写为属性访问:testFunction是模型定义的方法,必须用括号()来触发执行,直接写testFunction会被框架当成属性去读取,自然会报未定义的错误。

修正后的代码示例

Test_controller.php

class Test_controller extends CI_Controller {
    public function test(){
        $this->load->model('Test_model');
        // 修正两点:改用小写模型实例名 + 加上方法调用括号
        $test = $this->test_model->testFunction();
        echo "Message : " . $test;
    }
}

如果你偏好保留大写的模型实例名,也可以在加载时手动指定第二个参数:

// 加载模型时显式指定实例名称
$this->load->model('Test_model', 'Test_model');
// 此时就能用$test = $this->Test_model->testFunction();来调用

Test_model.php(无需修改,保持原代码即可)

class Test_model extends CI_Model{
    public function testFunction(){
        return "This is a test function on model";
    }
}

额外小提示

  • CodeIgniter官方建议模型文件名全小写(比如test_model.php),类名首字母大写,这样能避免不同服务器环境下的大小写兼容问题。
  • 务必确保模型文件放在application/models/目录下,否则框架无法定位加载。

内容的提问来源于stack exchange,提问作者jeesoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:13:21