If, like me, you come to PHP from a background in C, there is a big tripwire waiting to floor you ! - If you declare a variable global in PHP, that variable will NOT be available to your functions. - This had me in knots for hours yesterday and I just hope this post can save any other newbies from tearing out their hair trying to figure what happens. You always have to pass values to functions in PHP as parameters. - Chris
Interesting thing is, it seems to constrain one to write better code ! - It makes some parameter lists a bit lengthy but, when you read through the script, the localisation is more clearly seen which, I guess, means lower maintenance three months down the line ........ - - Chris
Chris: As a newcomer, let me suggest to you that php.net is great for documentation... eg. http://php.net/global for how to access / use global variables.
Global variables are not really advisable. And if you do use them, don't declare them outside of a PHP function. Declare them INSIDE your PHP function. If you're going to want values that can be accessed site wide, but not changed, use constants. DEFINE('CONSTANT_NAME','CONSTANT_VALUE'); That way they can be accessed site wide and don't have to be declared more than once. Just make sure you include a config file or something that contains your constants when needing them.
In PHP, that is I really want to know the deal with global variables (using global $var inside your function). Everyone seems to hate it, but from what I can tell it does not slow the script down, and it is definitely not insecure. So if someone could enlighten me?
well, like it was said before - you can access any variable as $GLOBALS['varname'] anyway. i guess a local global $varname is simply performing an extract() on $GLOBALS for that key to make it easier to access... but it also means changes applied to the variable during the function will keep when it returns. i cannot comment on memory usage but you can do tests: function Bollocks() { echo memory_get_usage() . "<br />" . substr($GLOBALS['a'], 0, 20); } Bollocks(); $a = str_repeat("Hello", 5000); Bollocks(); PHP: this outputs memory usage for before and after $a is defined, when using the GLOBALS array: 100200 // before 125376 // after HelloHelloHelloHello when decalared as global $a: global $a; echo memory_get_usage() . "<br />" . substr($a, 0, 20); PHP: 100416 // before is already higher by 216 bytes, just because...? 125688 // 312 bytes more allocated. HelloHelloHelloHello interesting. hrm...