• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
rookie question - Sharing variable between functions

I'm playing around trying to learn CI and so far it's great. I just have a question that is probably really basic. So I hope someone can point me in the right direction.

What is the best way to pass some data from one function to another in a controller?
If I have several functions and each one generates a status message when called. So how would I pass that message along to the index function. Or am I just completely daft and going about it all wrong?

Here's my test simple test code...


class Test extends Controller {
    function Test() {
        $this->load->helper(array('download', 'form', 'url'));
    function index() {
        if(isset($message)) {
            $data['message'] = $message;
            $data['message'] = 'No Message';
        $this->load->view('template', $data);
    // Upload the csv file
    function upload() {
        $config['upload_path'] = './upload/ahca/';
        $config['allowed_types'] = 'csv';
        $this->load->library('upload', $config);
        if ( ! $this->upload->do_upload()) {
            $message = $this->upload->display_errors();
        else {
            $data['data'] = array('upload_data' => $this->upload->data());
            $message = 'Successfully uploaded '.$data['data']['upload_data']['orig_name'];
        redirect('it/ahca', 'refresh');


Message could be a member of the controller class (in this case, Test). Instead of saying $message = "blah blah"; you would do $this->message = "blah blah blah". Since it is a member of the class, it doesn't go out of scope.

You should make a class variable of it if you want to share it between functions:
// instead of
$data['message'] = ...

// do this
$this->data['message'] =  ...

You also might want to take a look at my message library for passing messages around ;-)

Thanks Nelson, that looks like the simple answer I knew I was missing! I will give a go tonight.

n0xie's, your message library looks quite useful as well. Thanks man!

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.