Search
Left Quote    I start where the last man left off.
- Thomas A. Edison    
Right Quote
 
[login] | [Register]
 

Variable Scope

by: Umair
Page: 1 of 2
(View All)

Introduction

I 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 Examples

JavaScript 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.



1  |  2  |  
Next »


No Comments for this page.

You Must be logged in or a member to comment.


Tutorial Stats

Tutorial Stats

6,131 Views
0 Total Comments
4 Rating of 5 (1 Votes)

Options

Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Del.icio.us: Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article

Articles

Related    

· Simple PHP Tutorial
· One File Website
· Pagination with PHP
· Building a Comments Script
· Complete Members System


Homeowner Loan - Renegade motorhomes - New York Hotels - Debt Help

"AllSyntax.com" Copyright © 2002-2007; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank