Welcome Guest, Not a member yet? Register   Sign In
variable in function of view
#1

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

[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
#3

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

[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;
}
#5

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

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

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




Theme © iAndrew 2016 - Forum software by © MyBB