¿Por qué establecer la variable superglobal $GLOBALS['foo'] no funciona?

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!
}
?>

La advertencia es:

Notice: Undefined variable: foo

Cómo ?

preguntado el 31 de julio de 12 a las 13:07

3 Respuestas

Dentro de la función, $foo is out of scope unless you call it as $GLOBALS['foo'] vea la sección 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 :(

Lea las PHP documentation on variable scope y $GLOBALS documentación para mas ejemplos

Respondido 31 Jul 12, 13:07

You will need to refer to it via the $GLOBALS array all the time. Read about Alcance variable 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!
}
?>

Respondido 31 Jul 12, 13:07

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

Respondido 31 Jul 12, 13:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.