【问题标题】:Fatal error: Class not found in codeigniter致命错误:在 codeigniter 中找不到类
【发布时间】:2015-07-01 08:56:06
【问题描述】:

我在代码点火器的Application\core目录下创建了一个模型Admin_Model。我把所有基本的数据库操作都放在了它下面。当我尝试扩展 Application\model 目录下的模型时,它会引发错误。

Fatal error: Class 'Admin_Model' not found in <path to root>/application/models/new_model.php on line 3

我应该错过任何配置吗?

【问题讨论】:

  • 提交您的完整控制器和模型代码
  • Admin_Model 在模型文件夹中创建
  • 嗨@Random 我没有使用过 require_once 或任何其他代码。你想要什么额外的信息?请说明,我给你。
  • 您可能需要要求 /application/models/new_model.php
  • 核心文件夹中的文件需要以MY_ 开头,如config.php 文件中设置的那样。要制作您想要的,请搜索 Phil Sturgeon 的 Keeping it dry 文章,或者您也可以查看 this one

标签: php codeigniter


【解决方案1】:

如果您仍然无法使用 __autoload 来使用 来自库的类,这也可能会有所帮助。当我使用类库作为控制器的父类时,它对我有用。

PHP 5 >= 5.1.2, PHP 7

这是 mycode 在 application/config.php

spl_autoload_register(function ($classname){
    if(strpos($classname,'CI_') == 0){
            $file = APPPATH.'libraries/'.$classname.'.php';
            if(file_exists($file)){
                @include_once($file);
            }
    }
});

【讨论】:

【解决方案2】:

感谢大家的努力。 我找到了解决办法。

默认情况下,CodeIgniter 在其配置文件中有一个设置。

$config['subclass_prefix'] = 'MY_';

我只是将 'MY_' 替换为 'Admin_' 一切正常。

$config['subclass_prefix'] = 'Admin_';

更合适的解决方案是

  1. 将类文件放入库文件夹中
  2. 将以下代码添加到 config.php

    function __autoload($classname)
    {
    if(strpos($classname,'CI_') == 0)
    {
        $file = APPPATH.'libraries/'.$classname.'.php';
        if(file_exists($file))
        {
            @include_once($file);
        }
    }
    }
    

就是这样

【讨论】:

    【解决方案3】:

    扩展核心类

    如果您需要做的只是向现有库添加一些功能 - 可能添加一两个功能 - 那么用您的版本替换整个库就有点过头了。在这种情况下,最好简单地扩展类。扩展一个类与替换一个类几乎相同,但有几个例外:

    类声明必须扩展父类。 您的新类名和文件名必须以 MY_ 为前缀(此项是可配置的。见下文。)。 例如,要扩展本机模型类,您将创建一个名为 application/core/MY_Model.php 的文件,并使用以下命令声明您的类:

    class MY_Model extends CI_Model {
    
    }
    

    注意:如果您需要在类中使用构造函数,请确保扩展父构造函数:

    class MY_Model extends CI_Model {
    
        function __construct()
        {
            parent::__construct();
        }
    }
    

    【讨论】:

    • 如果我将我的模型命名为MY_Model,您的回答很好,但除此之外它不接受显示错误。即使我声明我的模型MY_Admin_Model 也会显示错误。
    • 核心模型仅扩展现有模型,这些模型位于文件夹 ../system/core/ - 例如 Lang、Input、Model... Admin_Model 不是核心模型,因此也是错误的。
    猜你喜欢
    • 2013-11-04
    • 2013-06-30
    • 2015-04-29
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    相关资源
    最近更新 更多