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

时间:2015-08-22 05:22:56

标签: php codeigniter model-view-controller helper

我正在codeigniter 3.0中创建一个Web应用程序。我在从codeigniter实例访问数据库对象时遇到问题,并像在模型中一样使用它。 我的代码是:

<?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);
   }

这显示我这样的错误

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

有没有合适的方法可以做到这一点? 请建议。

1 个答案:

答案 0 :(得分:1)

您需要在函数内声明$CI。在您的代码中,您在函数之外声明$CI =& get_instance();

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);
}