【问题标题】:how to use get_instance() in custom library file in codeigniter如何在codeigniter的自定义库文件中使用get_instance()
【发布时间】:2016-05-17 17:33:51
【问题描述】:

这是我在 codeigniter 库文件夹中的自定义类

class Commonlib {

        public function __construct()
        {      
                 $ci=& get_instance();
                 $ci->load->database();
        }
           function getcountries(){

                return  $ci->db->get("countries")->result();
            }
                function cities(){ 
                return  $ci->db->get("cities")->result();
            }
    }

这是我的看法

$results=$this->commonlib->getcountries();
   foreach ($results as $row)
   { 
       echo '<a   href="#">'.$row->country .'</a><br>';
   }

错误是严重性:通知消息:未定义的变量:ci 如何在库构造函数中加载数据库

【问题讨论】:

  • 尝试使用$this-&gt;CI 而不是$ci
  • 为什么在库中加载数据库自动加载autoload.php文件中的数据库,

标签: php codeigniter


【解决方案1】:

试试下面的代码。建议进行一些更改

class Commonlib {
    private $ci;
    public function __construct()
    {      
             $this -> ci=& get_instance();
             $this -> ci->load->database();
    }
       function getcountries(){

            return  $this -> ci->db->get("countries")->result();
        }
            function cities(){ 
            return  $this -> ci->db->get("cities")->result();
        }
}

注意:在您的旧代码 $db 中的 __construct() 方法将仅在该方法中具有作用域。为了在整个类中全局获取ci 对象,我使用了$this

【讨论】:

  • @GhulamAbbas,很高兴为您提供帮助。请投票并接受答案.. :) 以便其他人可以轻松找到答案
  • 使用这个有什么缺点吗?
【解决方案2】:

请尝试创建助手

在目录 app/helpers/ 中创建助手

layout_helper.php

function getcountries()
{

    $CI = & get_instance();     
    return  $CI->db->get("countries")->result();   
}

现在函数使用是查看文件 像这样:

$result = getcountries();

foreach ($results as $row)
{ 
   echo '<a   href="#">'.$row->country .'</a><br>';
}

【讨论】:

  • 我有城市,然后再写一次 $CI = & get_instance();因为你我有 100 个函数然后再次写 100 行但我想在整个文件中写一行
猜你喜欢
  • 2013-11-24
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多