Page 1 of 1

newbie - global variable

Posted: Fri Aug 20, 2010 6:56 pm
by stma
Hello EveryOne!
could someone please tell what I am doing wrong (if I am doing anything wrong at all)
I am confused with the global variables in PHP.

the following code works just fine
function testGlobal()
{
global $globvar;
$globvar=3;
echo " \$globvar: $globvar";
}
testGlobal();

and prints out the value of globvar on the page of browser.

however, if I assign the value to this variable on the same line I declare it - I am getting blank page in the browser.
function testGlobal()
{
global $globvar=3;
echo " \$globvar: $globvar";
}
testGlobal();

Am I doing something wrong? is it bug in PHP? is something wrong with my settings?
just in case, my settings/versions are:
uname -srvmo
Linux 2.6.18-194.11.1.el5 #1 SMP Tue Aug 10 19:05:06 EDT 2010 x86_64 GNU/Linux
PHP 5.3.3 (cli) (built: Aug 18 2010 12:08:14)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies


thank you in advance!

Re: newbie - global variable

Posted: Fri Aug 20, 2010 7:12 pm
by Gargoyle

Code: Select all

global $globvar;
$globvar = 3;
you should, however, rather use the $GLOBALS array because you can easily lose track of what variables have been defined as global.

Code: Select all

$GLOBALS['globvar'] = 3;

Re: newbie - global variable

Posted: Fri Aug 20, 2010 7:44 pm
by PHPHorizons
Hello stma,

The issue here is that unlike JavaScript's var keyword, global does not allow assigning a value to a variable.

Code: Select all

global $foo = 1; // syntax error and hence, a blank white screen

global $foo;
$foo = 1; // This is okay
Cheers

Re: newbie - global variable

Posted: Mon Sep 13, 2010 1:30 pm
by stma
Guys!
thank you very much for all your replies - I understood how it works! :)

cheers.

Re: newbie - global variable

Posted: Mon Sep 13, 2010 2:00 pm
by AbraCadaver
PHP would tell you this if it could:
[text]Parse error: syntax error, unexpected '=', expecting ',' or ';' in file.php on line X[/text]
So help PHP help you:

Code: Select all

error_reporting(E_ALL);
ini_set('display_errors', '1');

Re: newbie - global variable

Posted: Mon Sep 13, 2010 2:33 pm
by stma
Thank you Guys! - much appreciated!
I have another question, which administrator just moved to here:
viewtopic.php?f=31&t=121139

may you guys, could give me a hand with this one as well?

thank you in advance!