简体   繁体   中英

How do i properly create a function in a helper file in codeigniter

I am trying to learn code igniter and creating helper files. I have this as my functions_helper.php file located in my applications/helpers folder:

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

function __construct()
{
    parent::__construct();
    $this->load->model('user','',TRUE);
}
if (!function_exists('check_status')){

function check_status()
{
$CI = & get_instance();
    $result=$CI->user->get_status(); //this is line 14!!
        if($result)
    {
        $status_array=array();
        foreach($result as $row)
        {
            $status_array=array(
                'source' => $row->status,
                'current' => $row->id
                );

        if ($status_array['current'] == 1) {
    $status_array['current'] = "Live";
} else {
    $status_array['current'] = "Amazon is Down";
}

            $CI->session->set_userdata('status',$status_array);
        }
        return TRUE;


    }
    else
    {

        return false;
    }
} // END OF CHECK_STATUS FUNCTION
} 

From everything i can find, I am doing it correctly, yet I am getting this error:

PHP Fatal error:  Call to a member function get_status() on a non-object in function_helper.php on line 14. exactly what am i doing wrong?  Is this the best way to call a function?  Ultimately I am trying to get information returned from a db query.

My get_status function is:

//FUNCTION TO SEE THE STATUS OF AMAZON
function get_status() {

    $query = $this->db->query("select * from amz where active = 1");

    if($query->num_rows()==1) {
        return $query->row_array();
    }else  {
        return false;
    }
} //END OF GET_STATUS FUNCTION

Remove this code

function __construct()
{
    parent::__construct();
    $this->load->model('user','',TRUE);
}

There is no OO in helper files. You do not have a class - __construct() are used to initialize classes.

Then move

$this->load->model('user','',TRUE); to the check_status function

$CI =& get_instance();
$CI->load->model('user','','TRUE');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM