dslreports logo
 
    All Forums Hot Topics Gallery
spc
Search similar:


uniqs
596

Nordy
join:2007-10-20

Nordy

Member

Accessing a global $foo inside a function in php

I'm trying to access global $foo inside a function, but it wont work. I don't want to add it when calling the function. Whats a good way to do this?


global $foo;
$foo = 'norman';

The above code is in a separate file. The variable there is set at the time of login. This cannot be changed (they say).

The below is in another file. The above file is included in the one below.

function kit($name)
{
if($foo == $name){echo 'Works';}else{echo 'Does not work';}
}
kit('norman')


$foo, being a global variable should have worked. Right? Why isn't it working here? And how to do this correctly?

Thanks

Toad
join:2001-07-22
Bradford, ON

Toad

Member

Need to declare $foo as global within the function.

function kit($name) {
  global $foo;
...
 

Nordy
join:2007-10-20

Nordy

Member

No problems if I declare it within the function as well as in the include file?

Mospaw
My socks don't match.

join:2001-01-08
New Braunfels, TX

Mospaw

You'll be fine. Just don't redefine it. :)

To elaborate on what Toad See Profile posted...

function kit($name) {
    global $foo;
    ...
}
 

The "global $foo;" line is what brings the global $foo into the scope of kit(). Declaring $foo global outside of that function actually has no effect.

Nordy
join:2007-10-20

Nordy

Member

Hmm... Well, Thanks to both of you. I'll see how it got that way in the first place