Page 1 of 1
global variable question
Posted: Sun Jan 02, 2005 2:37 pm
by irishmike2004
I was looking over my first real PHP script ( I wrote it almost 2 months ago) and I have a silly question.
If I want a variable to be global (that is live both inside and outside of a function) can you define it as global then use it inside of functions?
For example:
Code: Select all
<?php
global $someVariable;
function foo()
{
$someVariable = "bar";
}
?>
as opposed to the way it is now:
Code: Select all
<?php
$someVarible;
function foo()
{
global $someVariable;
$someVariable = "bar";
}
?>
I think that would make it so I only have to define it once as global instead of in the case of my script where there are 20 some variables and the list has to be maintained both inside and outside the function...
Thanks,
Posted: Sun Jan 02, 2005 3:18 pm
by neophyte
This page has the answers you are looking for....
http://us2.php.net/manual/en/language.v ... .scope.php
You can also change the value of a variable outside of a function by passing it by reference.
Code: Select all
<?php
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
?>
The little ampersand does the trick....
Posted: Sun Jan 02, 2005 7:44 pm
by rehfeld
yeah you should consider passing the variables through the function itself.
that way you dont need to change your functions if you ever change the name of the variable.
i almost never use the global statement inside of a function,
if i need to do that i always feel im not using functions correctly.
theres def exceptions but i havent found many.
if you need to call global on a ton of variables inside a function,
maybe consider using an include so your code will inherit the scope and there will be no need for calling global then...
but to answer your initial question, no, there is no way to declare a variable as a superglobal.
however, you could put the variable into an existing superglobal like _SESSION, but thats
a really smurfy way to do things....
use functions how they were meant to be used, pass variables through the function itself.
feyd | watch the language
Posted: Sun Jan 02, 2005 8:32 pm
by feyd
if it's a global already, then the variable is already in the $GLOBALS superglobal..
I'd pass the variable in too, though.
Posted: Sun Jan 02, 2005 8:57 pm
by irishmike2004
cool thanks gents