开发者

"Global" variable scope in PHP

I have a section of code like the following:

---- file.php ----

require_once("mylib.php");

function($a,$b)
{
    $r = $_GLOBALS['someGlobal'];
    echo $r;
}

---- mylib.php ----

$_GLOBALS['someGlobal'] = "Random String";

This is a bit trivialized, but is the exact problem I have an I haven't found some related stuff, but nothing that answers my question directly.

When I call function($a,$b) nothing is echo'd, that is - $r is "empty" as if开发者_开发技巧 nothing was ever assigned to $_GLOBALS['someGlobal'];

In addition, I have tried with the following:

global $someGlobal;
$someGlobal = "Random String";

Same thing, no effect. Also, in file.php if I try with global, or with just $someGlobal it still does not work.

As far as I know, from the documentation on php.net using global $someGlobal in mylib.php (and having that inserted in the top level of file.php) that it would not actually do much since it's already at the "top-level" of the scope hierarchy as far as I can tell. However, I thought registering it as a global might allow it to be accessed from inside the function, but this is clearly not the case.

Can anybody explain why, and explain how to get around this?

Edit: I should not that in file.php if I use $_GLOBALS['someGlobal']; the value is recovered fine if it's not in a function.


Wrong variable name. It's $GLOBALS not $_GLOBALS

http://www.php.net/manual/en/reserved.variables.globals.php


From the docs, there is no _ in the $GLOBALS variable:

This works fine for me:

$GLOBALS['glob'] = "string";

function foob() {
  echo $GLOBALS['glob'];
}

foob();


It's $GLOBALS, not $_GLOBALS!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜