Okay, I'm not sure I'm understanding this concept properly (I'm learning PHP). If I understand correctly: Global variables can be referenced anywhere in the same document, or in documents linked with "include." Local variables can only be referenced in the function where they are.
Okay, if I understand that correctly (which is half of the reason I'm posting, to make sure I have that right) is there really a need for local variables? I mean, if each user defined their own variables and they needed to all be saved, I can see it being useful... kind of? But, using a database for that would be much simpler I'd think. What situations would I want to use local variables in?
Variables are classified into Global variables and Local variables based on their scope. The main difference between Global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only within the function or block in which they are defined.
It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls. If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.
You're question was making sense right up to the point where you asked for the need of local variables. On the whole, you should avoid global variables as much as you can.
It's not uncommon for me to write some tool/webapp and have only two or three of my own global variables, that I use to set the actual application in motion.
Consider this:
$db = new PDO($conn, $usr, $pass);
function select(array $fields, $tbl, $where = '')
{
global $db;//use the global variable
return $db->query('SELECT '.implode(', ', $fields).' FROM '.$tbl.' WHERE '.$where);
}
In itself, you might argue that this code will work fine all the time. It's clear what $db
is, and so there's no obvious error here.
However, suppose you include a couple of other files that use the same $db
var, and there's a bug in one of those files, that causes $db
to be reassigned:
$db = 'I used to be a PDO instnace';
select(array('*'), 'tbl');
This will show an error that will point you to the line that reads return $db->query();
and it'll say something like "trying to call method of non-object".
Good luck debugging that! Where was $db
reassigned? there's no way to know except for sifting through your code step by step.
It might still be where you last left it, but chances are its state (or value) has been changed (significantly) by some other entity/entities (people or code), who might have used your wallet (or variable) as their own, blissfuly unaware you left it there for future reference. When writing classes or functions, you refer to your collegues who will use that code as the user, too. So even if they meant no harm, a global is an accident, waiting to happen.
Incidentally, the function arguments are local variables, so I'm sure you're using them already, without knowing it.
It'd be far better to define the select
function as follows:
function select(PDO $connection, array $fields, $tbl = 'tbl', $where = null)
{
$query = 'SELECT '.implode(', ', $fields).' FROM '.$tbl;
$query .= $where !== null ? ' WHERE '.$where : '';
return $connection->query($query);
}
In this funciton I've created a local variable to make the code more readable/maintainable. Like I said, all the arguments are local variables, too, so after this function returns, any memory that was allocated to accomodate the values they held can be freed. When you're using global variables, the Garbage Collector can't do its job, because the variables remain in scope, and might be used further down the code. The memory is only freed once the script has finished running.
Globals (vars in the global scope) make for messy code, as you try to avoid name conflicts, you're going to find yourself declaring vars like $i_for_looping_over_array1 = 0;
Ok that might be a bit extreme, but you'll end up pseudo-namespacing your vars anyway, so why not use proper namespaces, scopes, classes, etc.?
global
keyword is slowWhenever you use the global
keyword inside a function, you're effectively saying: look for a variable called $someName
, which can be anywhere. Passing that same variable as an argument, is telling the function use this.
When passing an object, you're actually passing a reference to that object (ie its address), so there's no lookup required. Primitives are copied, so there's no lookup either.
Think of yourself as a bartender. Where would you rather work? Pub AllIsGlobalHere, where, on your first day, your boss said: "If a customer asks for something, the bottle could be anywhere, the cellar, the floor or the top-right cupboard", or Pub CheckTheArguments. The latter being the place where you jump right in, and when a customer asks for a beer, your boss and/or customer helpfully point out which draught you should refer to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With