[thelist] Global variables in functions?

Kelly Hallman khallman at wrack.org
Wed Aug 20 00:50:48 CDT 2003


On Tue, 19 Aug 2003, David Bindel wrote:
> > function body() {
> >   $url = 'http://server/script.php?'.$_SERVER[QUERY_STRING];
> >   $output = file_get_contents ($url);
> >   echo $output; }
> 
> That's because $output is in the scope of that function.  In the
> previous code chunk you gave, $output was outside of the scope of the
> function (except through the $GLOBALS array.)

Also, you can use the 'global' statement:

function body() {
    global $url;
    $output = file_get_contents($url); }    

It's important to understand the namespace/scoping rules, as it can save a
lot of debugging time.  (If it seems like a pain, it's actually a good
thing, and PHP is not really strict enough in this regard.)

It would also not be a bad idea to make the function more reusable by
passing the value as an argument, and avoid the whole mess:

function body($url) {
    $output = file_get_contents($url);
    return $output; }

$url = 'index.html';
echo body($url);

-- 
Kelly Hallman
http://wrack.org/





More information about the thelist mailing list