简体   繁体   中英

Codeigniter - Accessing variables from a helper file - not a class

I have a helper file, it has a variable that I want to pass across to a view, but it comes across as empty, so I am a bit unsure if I have the right code or I have overwritten it later on _ though I am sure I have not!

anyway say the variable in ther helper file is an array that contains a list of data, and I use:

$this->load->helper('helperfile_helper'); //contains the variable 'productList'
$data['productList'] = $productList;
$this->load->view('page', $data);

I would expect that the helper file works like an 'include' with the defined variables available once the helper has been called, is this the casee or have I missed something??

Helpers allow you to use function in your controller, have a look here: http://ellislab.com/codeigniter%20/user-guide/general/helpers.html

So you must create a function in your helper file that will return a value.

For example in your helper:

if( ! function_exists('random_number'))
{
    function random_number()
    {
return 4;
    }
}

and in your controller you can use it:

$this->load->helper('helperfile_helper'); //contains the variable 'productList'
$data['random_number'] = random_number();
$this->load->view('page', $data);

So $data['random_number'] will contain 4

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