variable in function of view - 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: variable in function of view (/showthread.php?tid=1946) |
variable in function of view - El Forum - 07-06-2007 [eluser]shkim[/eluser] I want to use a variable $abcde in a function of a view like the following code: --------------------------------------- controller: $data['abcde'] = 1; $this->load->view('myview', $data); myview: function xxx() { $yyy = $abcde; <-- undefined variable error } $zzz = $abcde; <-- ok --------------------------------------- What's wrong with me? variable in function of view - El Forum - 07-06-2007 [eluser]kgill[/eluser] Your problem is scope... The variables passed to the view are global, if you use $abcde in a function like that - it is then referencing a local variable not the global version. stick a global statement in so it knows where to find the value Code: function xxx() - K variable in function of view - El Forum - 07-06-2007 [eluser]shkim[/eluser] I tried 'global' but it did not work. (in PHP5) There was no 'undefined' error but the variable in the function was empty. variable in function of view - El Forum - 07-06-2007 [eluser]kgill[/eluser] Ok I poked around and it appears that the values passed to the view in the data array aren't actually global. So either you drop the function idea (should it really be in a view anyway?) or you pass params or you do a really ugly hack: Code: global myNewVar; variable in function of view - El Forum - 07-07-2007 [eluser]pr0digy[/eluser] I don't think you should use functions within views - there are helpers and such if you need to automate repetitive tasks. variable in function of view - El Forum - 07-07-2007 [eluser]shkim[/eluser] Thanks. I thought about making a helper, but there was too many argument passing, and it was so simple and specific that no other views shared it. variable in function of view - El Forum - 07-07-2007 [eluser]Developer13[/eluser] If the variable is going to be the same as something passed from the controller, then why not set it in the controller? Am I missing something here? |