Access Codeigniter data variables in function inside a view Access Codeigniter data variables in function inside a view codeigniter codeigniter

Access Codeigniter data variables in function inside a view


in your controller:

    $GLOBALS['var_available_in_function'] = $value;

Your function:

    function get_var() {       global $var_available_in_function;       return $var_available_in_function;    }


I tried this but using globals in my view someview.php doesn't work..

function func_in_view(){  global $info;  print_r ($info); // NULL}

You may need to pass this as a parameter instead to your function so it's available to it.

function func_in_view($info){  print_r ($info); // NULL}

I read this method $this->load->vars($array)
in http://codeigniter.com/user_guide/libraries/loader.html
but it's purpose is just to make it available to any view file from any function for that controller. I tried my code above global $info; and it still doesn't work.

You may need to do the workaround by passing it as a parameter instead.
Try including this in your someview.php => print "<pre>";print_r($GLOBALS);print "</pre>"; and the variables passed through $this->load->view aren't included.


I solved this by creating a global variable within the view, then assigning the passed in $data value to the global variable. That way, the information can be read within the view's function without having to pass the variable to the function.

For example, in the controller, you have:

$data['variable1'] = "hello world";$this->load->view('showpage',$data);

Then in the showpage.php view, you have:

global $local_variable = $variable1;function view_function() {  global $local_variable;  echo $local_variable;}view_function();

Hope this helps!