duanbo6871 2015-08-22 05:22
浏览 59
已采纳

如何在帮助文件中访问codeigniter对象和变量?

I'm creating a web application in codeigniter 3.0. I have a problem accessing database object from codeigniter instance and use it as we do in model. My code is:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$CI =& get_instance();
$CI->load->database();
function get_menu($slug)
 {   
   $CI->db->select('menuid');
   $CI->db->where(array('slug'=>$slug));
   $query=$CI->db->get('menus')->row();
   echo  $menuid= $query->menuid;
   $query="SELECT * FROM menu_items WHERE menuid=".$menuid;
   write_menu($query);
   }

This show me error like this

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: CI

Filename: helpers/menu_helper.php

Line Number: 9

Backtrace:

File: C:\Users\Pradeep\Google Drive\control\helpers\menu_helper.php
Line: 9
Function: _error_handler

File: C:\Users\Pradeep\Google Drive\control\controllers\Welcome.php
Line: 19
Function: get_menu

File: C:\Users\Pradeep\Google Drive\index.php
Line: 292
Function: require_once

Is there any suitable method to do this ? Please suggest.

  • 写回答

1条回答 默认 最新

  • doushen2154 2015-08-22 05:34
    关注

    You need to declare you $CI inside your function. In your code you declare $CI =& get_instance(); outside your function

    function get_menu($slug)
    {
        $CI =& get_instance();
        $CI->load->database();
        $CI->db->select('menuid');
        $CI->db->where(array('slug' => $slug));
        $query = $CI->db->get('menus')->row();
        echo $menuid = $query->menuid;
        $query = "SELECT * FROM menu_items WHERE menuid=" . $menuid;
        write_menu($query);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作