FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Global variables





Denvis
How do I indicate that a variable is global? Also, why do people avoid using global variables?

Edit: Also, am I allowed to declare a global variable within a sub module and then use that variable within another sub module?
Nemesis234
http://php.net/manual/en/language.variables.scope.php

i wasnt aware people avoided them, i never use them personally but then i dont use many functions in my code
jmraker
I guess people avoid them because they are trying to make their functions not affect the main code.

If a function uses the global variable "$type" and changes it like
Code:

<?php

function setSomething($a){
  global $type;
  $type .= $a;
}

$type = 'abc';
....
setSomething('xyz');
....
echo $type;
?>


the value of $type would be 'abcxyz' which might be unexpected and they'd have to figure out why $type isn't 'abc';

When I have to use global variables I name them something obscure like $__typeString that isn't likely to be used later and cause problems.
Fire Boar
In PHP variables are "semi-global", I suppose you could say. You have to explicitly say "I want this variable to be used globally" using the "global" keyword or the $GLOBALS variable.
AftershockVibe
Denvis wrote:
How do I indicate that a variable is global? Also, why do people avoid using global variables?


Fire Boar has said how you can declare them (so PHP knows what's going), but if you're not explicitly using $GLOBALS then it can get very confusing for the programmer. This is the same reason why people tend to avoid them since usually they're not necessary.

Imagine a global variable named "$num". That could be anything, from any context, from anywhere, of any scope. Even if you know what the data is supposed to be used for, you have no idea what other code might break if you change its value. This is why global variables (especially stupid ones like this) are frowned upon. If there's a stigma about using them then it forces programmers to think whether they are really necessary or whether something can be achieved with better clarity.
Related topics
php + forms + variables
Flash script problem
extremely short SESSION lifetime
php error ?[parse error]
PHP question, $_SESSION[] gets changes to by $_POST var
PHP Problem...
Online Store
phpNuke Register new users Problem Problem
Hot Or Not script not working
destroy\unset sessions?
Help with Dreamweaver sessions !!!!!!!!
How to make Global Variables with PHP?
Global variables in jommla 1.0.x?
enumerating global vars
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.