Access Codeigniter data variables in function inside a view

感情迁移 提交于 2019-12-10 16:32:34

问题


I have a function in one of my views, and I want to access one of the variables available to the view through CodeIgniter's data array.

For example; in my controller I have this:

$this->load->view('someview', array(
    'info' => 'some info'
));

Now, within my view, I have a function, and I want to be able to access the variable $info from within that function scope.

Is that possible?


回答1:


in your controller:

    $GLOBALS['var_available_in_function'] = $value;

Your function:

    function get_var() {
       global $var_available_in_function;

       return $var_available_in_function;
    }



回答2:


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.




回答3:


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!



来源:https://stackoverflow.com/questions/6983907/access-codeigniter-data-variables-in-function-inside-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!