Re: Global unavailable?
| From: | Jochem Maas | Date: | Wed, 05 Oct 2005 12:37:53 +0000 |
| Subject: | Re: Global unavailable? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-223647@lists.php.net to get a copy of this message | ||
Marcus Bointon wrote:
I have a simple situation:
in a.inc.php:
$a = 1;
in b.class.php
require 'a.inc.php';
class b {
function test() {
global $a;
echo $a;
}
}
With this pattern, $a is NOT visible within class b, even though it is declared in the global scope and I'm using the global keyword! I can work around it two ways; by changing the original declaration (which just seems wrong - it's already in the global scope at this point):
global $a;
$a = 1;
if changing the declaration in a.inc.php fixes it then you must
NOT be including b.inc.php form the global scope. which means $a will not
be in the global scope unless you tell php to put it there, instead $a
is probably part of a function scope.
e.g. you have a function like so:
function getNewBee()
{
require_once('b.inc.php');
$b =& new b;
return $b;
}
in the above $a lives in the scope of the function call to
getNewBee() and NOT in the global scope.
or by requiring the inc file inside each function of b (much less efficient):
class b {
function test() {
require 'a.inc.php';
doing it like this means you don't need to specify
$a as 'global' - its already in the scope of the current function
(method), specifying it as 'global' will make it available everywhere
though.
global $a;
echo $a;
}
}
Is this just how it is, or am I doing something wrong?
Marcus