Global variables and local variables

Well, I'm not sure I understand this concept correctly (I'm learning PHP). If I understand correctly: Global variables can be referenced anywhere in a single document or in documents related to "include". Local variables can only refer to the function in which they are located.

Well, if I understand correctly (which is half the reason I send a message to make sure that I have this right), is there really a need for local variables? I mean, if each user defined their own variables, and they had to be saved, I see that this is useful ... sort of? But using a database for this would be much easier, I would think. In what situations would I like to use local variables in?

+6
source share
6 answers

You doubt that you asked about the need for local variables. In general, you should avoid global variables as much as you can.

I often write some kind of tool / webapp and have only two or three of my own global variables, which 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); } 

By itself, you can argue that this code will work fine all the time. It is clear that $db , and therefore there is no obvious error.
However, suppose you include several other files that use the same $db var, and there is an error in one of these files, which leads to the reassignment of $db :

 $db = 'I used to be a PDO instnace'; select(array('*'), 'tbl'); 

This will show an error that will point you to a line that reads return $db->query(); , and she will say something like "trying to call a non-object method."

Good luck debugging this! Where was $db reassigned? There is no way to find out other than sifting through your code step by step.

The announcement of the entire Global is like leaving your wallet for a walk every night.

It may still be possible the last time you left it, but the likelihood that its state (or value) was changed (significantly) by any other entity / entities (people or code) that your wallet could use ( or variable) as their own, blissfuly does not know that you left it there for future use. When writing classes or functions, you turn to your colleagues who will use this code as a user. Therefore, even if they do not harm, the global case is an accident awaiting its service.

By the way, function arguments are local variables, so I'm sure you already use them without knowing it.

It would be much 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 created a local variable to make the code more readable / supported. As I said, all arguments are also local variables, so after returning this function, any memory that was allocated to hold the values ​​that they held could be freed. When you use global variables, the garbage collector cannot do its job because the variables remain in scope and can be used further in the code. Memory is freed only after the script completes.

Globals tell the garbage collector to "wait a minute" every time it tries to free memory because a script will need a variable later. Code complete with globals is a bit of a write.

Globals (vars globally) do for dirty code, as you try to avoid name conflicts, you will find that you declare vars as $i_for_looping_over_array1 = 0;

It’s good that this can be a bit extreme, but you’ll end up pseudo-name your varna, so why not use the right namespaces, regions, classes, etc.?

global keyword usage is slow

Whenever you use the global inside a function, you effectively say: find a variable called $someName , which can be anywhere. Passing the same variable as the argument, says the function uses this.

When transferring an object, you actually pass a link to this object (i.e. its address), so a search is not required. Primitives are copied, so there is no search.

Think of yourself as a bartender. Where would you rather work? Pub AllIsGlobalHere, where on your first day your boss said: “If a client asks for something, the bottle can be anywhere, a basement, floor or upper right cupboard” or “CheckTheArguments Pub”. The latter is the place where you jump directly, and when a client asks for beer, your boss and / or client will be happy to indicate which project you should refer to.

+8
source

Local variables are necessary for encapsulation, which is good programming practice.

Global variables are actually bad practice because the variable can be changed anywhere in the application and, believe me, it’s hard to debug why the value of the variable is not expected if you have multipliers with multipliers ...

If you need to use a global variable, perhaps you should consider using a singleton or passing the variable as a parameter to the function that needs it.

+2
source

In programming, there are many cases where you need a variable only in an isolated context. Counters, function arguments and variables for storing intermediate results of calculations, etc., They are not of interest to the entire application. In addition, there is a special case of recursive functions. Local variables will receive their own different addresses for each instance of the recursive function, which is necessary for the recursion to work correctly. However, in PHP applications, it is recommended that you avoid using global variables wherever you can.

+1
source

Only a few reasons to prefer local over gobal:

Variables take up memory. If each variable is global, it takes up a lot of memory. Local variables exist only when they are in scope, so they temporarily use memory, and then memory is freed again. Therefore, it is better to use memory - a good argument.

If all the variables are global, then function A and function B can update the variable, but no one knows that the other has changed it, so this can lead to situations where you do not understand what value was changed to one function, and assume that it still valid in another.

0
source

In what situations would I like to use local variables in?

Local variables are those that are defined inside the local area (function), these variables are available only in this area, but not outside, for example:

 $foo = 'foo'; function bar(){ $foo = 'bar'; } echo $foo; //prints foo 

for example, you can see that the same variable name can be used inside the local area without any changes.

0
source

If you use only global vars, you need to specify a new name for each new counter, haha.

The visibility of vars is necessary for encapsulation: only the object you want to access can affect a variable. For instance:

 class Person{ private $_money; public function rob(){ return $this->_money; } } 

Only an object of class Man can manage his money, so if you want them, you must get a mask and a gun.

0
source

Source: https://habr.com/ru/post/950796/


All Articles