• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
variable in function of view

I want to use a variable $abcde in a function of a view like the following code:

$data['abcde'] = 1;
$this->load->view('myview', $data);

function xxx()
$yyy = $abcde; <-- undefined variable error

$zzz = $abcde; <-- ok


What's wrong with me?

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
function xxx()
global $abcde;
$yyy = $abcde;

- K

I tried 'global' but it did not work. (in PHP5)

There was no 'undefined' error but
the variable in the function was empty.

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:

global myNewVar;
myNewVar = $abcde;

function xxx()
global $myNewVar;
$yyy = $myNewVar;

I don't think you should use functions within views - there are helpers and such if you need to automate repetitive tasks.

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.

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?

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.