Forum Moderators: coopster

Message Too Old, No Replies

Where to declare Global Vars

         

neophyte

11:01 am on Jan 1, 2010 (gmt 0)

10+ Year Member



Hello All -

This may sound kind of strange, but I'm not really sure of the best "place" to declare a global var.

For instance, if I know I'm going to use a certain var in various functions - and don't necessarily want to literally pass the var to these functions - would it work to declare the var global in the index?

Sort of declare once - use anywhere? Or would I still need to re-declare this same var as a global in each function I'm using it in?

Neophyte

Frank_Rizzo

6:01 pm on Jan 1, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You have to declare it in each functions that you wish to use it.

$a = "test \n";

widget();
foo();
bar();

function widget() {

global $a;
echo $a;

}

function foo() {

global $a;
echo $a;

}

function bar() {

echo $a;

}

That will output

test
test

There is no output for bar() function as it does not know var $a

Psychopsia

6:08 pm on Jan 1, 2010 (gmt 0)

10+ Year Member



Hi neophyte!

If you don't want to declare 'global $a_var' for each function, you can use $GLOBALS['a_var'].

Take a look the PHP manual: [us.php.net...]

neophyte

2:56 am on Jan 2, 2010 (gmt 0)

10+ Year Member



Frank and Psychopsia -

Thank you both for your replies and information - Psychopsia: I'd heard about $GLOBALS before but never knew it could be used like that; appreciate the link.