![]() |
|
||||||
IntroductionI routinely see new programmers running into trouble with the concept of variable scope. It’s an extremely important concept, however, and one that must be understood in order to develop a reliable application. If you work in multiple programming languages, it can get even more confusing—each language has its own set of rules about how variable scope is handled.First of all, what is variable scope?Essentially, variable scope describes when a piece of information is accessible. When a variable is created, the value it stores is only available for a certain part of the code execution. Memory is set aside to store that piece of information and then freed when it is no longer needed.When traveling between two countries, you declare your goods at the border. Apply this analogy and declare variables at the border of the function—that is, right when you get into a function. When all variables are always available, memory is wasted because it is set aside well before or after it’s needed. This also causes a lot of confusion when a programmer needs to recall used variable names. So, we have scope. Scope ExamplesJavaScript and PHP do not require you to declare a variable before use. This can be handy when you just need to get something done but problematic when troubleshooting.For example, in JavaScript, a variable declared outside of a function is available inside a function: A variable declared within a function will not be available outside of a function. Confusion can really begin to set in when using the same variable name inside and outside of a function. Some languages have syntax to prevent these types of errors from occurring. In PHP, for example, to use a global variable inside a function, you must use the global keyword. Global variables are accessible even within multiple include files.
No Comments for this page. |
|
|||||||||||||||||||||||||||||||||||