English 中文(简体)
"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!





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签