CodeIgniter Forums
rookie question - Sharing variable between functions - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: rookie question - Sharing variable between functions (/showthread.php?tid=29623)



rookie question - Sharing variable between functions - El Forum - 04-15-2010

[eluser]zoonix[/eluser]
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...

Code:
<?php

class Test extends Controller {
    function Test() {
        parent::Controller();
        $this->load->helper(array('download', 'form', 'url'));
    }
    
    function index() {
        if(isset($message)) {
            $data['message'] = $message;
        }
        else{
            $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');
    }
}

Thanks!


rookie question - Sharing variable between functions - El Forum - 04-15-2010

[eluser]nelson.wells[/eluser]
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.


rookie question - Sharing variable between functions - El Forum - 04-15-2010

[eluser]n0xie[/eluser]
You should make a class variable of it if you want to share it between functions:
Code:
// 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 ;-)


rookie question - Sharing variable between functions - El Forum - 04-15-2010

[eluser]zoonix[/eluser]
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!