Question

The following code produces a warning:

<?php
$GLOBALS['foo'] = "Example content<BR><BR>";
echo $foo; // that works!
Test();

function Test()
{
    echo $foo; // that doesn't work!
}
?>

The warning is:

Notice: Undefined variable: foo

How come ?

Was it helpful?

Solution

Inside the function, $foo is out of scope unless you call it as $GLOBALS['foo'] or use global $foo. Defining a global with $GLOBALS, although it improves readability, does not automatically reserve the variable name for use in all scopes. You still need to explicitly call the global variable inside lower scopes to make use of it.

function Test()
{
    echo $GLOBALS['foo'];

    // Or less clear, use the global keyword
    global $foo;
    echo $foo;
}

It's even possible to have both a local and a global $foo in the same function (though not at all recommended):

$GLOBALS['foo'] = "foo! :)";
function getFoo()
{
  $foo = "boo :(";
  echo $GLOBALS['foo'] . "\n"; // Global $foo
  echo $foo;            // Local scope $foo since it has no global keyword
}

getFoo();
// foo! :) 
// boo :(

Review the PHP documentation on variable scope and the $GLOBALS documentation for more examples.

OTHER TIPS

You will need to refer to it via the $GLOBALS array all the time. Read about variable scope to get the full descriptve answer.

<?php
$GLOBALS['foo'] = "Example content<BR><BR>";
echo $foo; // that works!
Test();

function Test()
{
    echo $GLOBALS['foo']; // that doesn't work!
}
?>

you can change your code to:

function Test() {
    global $foo;

    echo $GLOBALS['foo'];
    echo $foo;
}

you have to declare which global variables you access from your PHP function. See: http://php.net/manual/en/language.variables.scope.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top