CodeIgniter Forums

Full Version: variable in function of view
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[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?

El Forum

[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()
{
global $abcde;
$yyy = $abcde;
}

- K

El Forum

[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.

El Forum

[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;
myNewVar = $abcde;

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

El Forum

[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.

El Forum

[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.

El Forum

[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?