crazy_php
crazy_php

Reputation: 23

How to declare global variable in CodeIgniter 2.2?

I have a controller in CodeIgniter like this

class C extends CI_controller {

    public function A()
    {
        var $data;
    }

    public function B(){
        //here i need to access the variable $data;

    }
}

How to do that in CodeIgniter? I can use a session. Is it really a good thing to assign that variable in a session? Is there any better way to declare the global varaibles?

i used like this but not working y

class C extends CI_controller {

        public $data;              
        public function A()
        {
            $this->data=1;
        }

        public function B(){
            //here $this->data showing null value y

        }
    }

Upvotes: 1

Views: 11422

Answers (4)

hyubs
hyubs

Reputation: 737

The 2nd block of code you have will not work if you have this scenario: Enter page C/A then enter C/B. Once a page is done, you won't be able to use the values you stored in global variables.

Try using sessions or flashdata. Flashdata is similar to a session except it disappears after the next page call.

Here's the CI page for sessions and flashdata for reference: http://codeigniter.com/user_guide/libraries/sessions.html

Upvotes: 0

rabidmachine9
rabidmachine9

Reputation: 7965

You should try and set some variables on a config file then you just include that file on your controllers constructor and you can access these variables from any view you want... http://codeigniter.com/user_guide/libraries/config.html

Upvotes: 1

J0HN
J0HN

Reputation: 26921

Use CI's session helper:

class C extends CI_controller {

    public function A()
    {
        $this->load->library('session');
        $data = array('data'=>$data); //set it
        $this->session->set_userdata($data);
    }

    public function B(){
        $this->load->library('session');
        $this->session->userdata('data'); //access it
    }
}

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96258

Global variables only exist in the lifetime of the request. Since for one request there's only one function executed in the controller (or you doing it the wrong way!) global variables won't work.

You have to put it into session or in database.

Upvotes: 3

Related Questions