Why are all my variables global? [solved]

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nutkenz
Forum Contributor
Posts: 155
Joined: Tue Jul 19, 2005 12:25 pm

Why are all my variables global? [solved]

Post by nutkenz »

Some test code:

Code: Select all

$variable= "BLABLA"; 
echo"<PRE>";print_r($GLOBALS);echo"</PRE>";
Output (relevant part only):

Code: Select all

Array ... [variable] => BLABLA
phpinfo():

Code: Select all

register_argc_argv On On 
register_globals Off Off
Last edited by nutkenz on Tue May 15, 2007 4:50 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Your variables are defined in the global scope. Of course they are global.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Globals are globals, that cannot be changed. $GLOBALS["foo"] is a geniune alternative to accessing $foo in the global namespace. No hacks there. What register_globals does is takes items from the superglobals $_POST, $_GET, $_REQUEST... and adds them to the global namespace directly so $_POST["foo"] is available as just $foo in the global namespace.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Another example to hopefully clarify

Code: Select all

<?php
$myvar1 = 'This is my variable. This is global';

function dummyTest()
{
   $myvar2='This is a local variable (scope only in this function)';
   echo   $myvar1; // Produces no output and a php warning    
   return $myvar2;
}

echo $myvar1; // prints out as not in function and declared globally
echo $myvar2; // Produces no output and a php warning as the variable is defined in the function and is local to that function.
echo dummyTest();  // prints out the value of $myvar2 as it is returned from the function.
?>
Variable Scope in manual
nutkenz
Forum Contributor
Posts: 155
Joined: Tue Jul 19, 2005 12:25 pm

Post by nutkenz »

It's funny that I didn't know about that... :)

Thanks everyone.
Post Reply