Coldfusion Tutorials



Spry Tutorials

Air Tutorials


Variable Scope

Since I just introduced the <cfset> tag and variables to you I should also tell you about scope. Scope in the context of variables is very important. You can think of scope as a named container where variables are stored. All variables in a particular scope must have unique names but you can have the same variable name in several different scopes. I am sure you can see how this could be a bad thing!

<cfset form.firstname="betty">
<cfset request.firstname="frank">
<cfset variables.firstname="bob">
<cfset application.firstname = "susy">
<cfset url.firstname="julie">

All the above variables are valid and unique in their own scope and I specified the scope of the variables by prefixing the name of the variable with the scope name as in <scopename>.<variablename>.

In Coldfusion there is an order of precedence when it comes to scopes, so if you don't specify the scope of the variable when you reference it Coldfusion must search through all the scopes looking for your variable in the following order:

  1. Arguments
  2. Variables
  3. CGI
  4. Cffile
  5. URL
  6. Form
  7. Cookie
  8. Client

As you can see from the list above, if you have a Form variable and you reference the name of the variable without specifying the scope Coldfusion Server first looks to see if your variable exists in 5 other scopes before finding it in the Form scope. According to Macromedia this can have an impact on performance.

When you submit a form all of the form fields create variables within the form scope that match the names of the input fields that you have on an HTML form. Likewise if you have a URL that has a name/value pair as in ID=23 you will have a variable in the URL scope called ID with the value of 23.

When accessing variables, therefore, it is important to prefix the name of the variable with the scope you are expecting this makes it a lot easier to debug your code and prevents you from having to figure out scope precedence.

So in the mess of cfsets above to output the correct firstname from a submitted HTML form you would do the following:

<cfoutput>#form.firstname#</cfoutput>

When you create a variable without using the scope prefix it is created in the local scope the name of this scope is the variables scope – or scope #2 in the list above.

<cfset firstname="bob">

Can be output as:
<cfoutput> #variables.firstname# </cfoutput>

Or:
<cfoutput> #firstname#</cfoutput>

In conclusion, knowing how variable scope works is important but correctly scoping the variables you create and using scope whenever you reference variables is, in my opinion, even more important than having the scope precedence order memorized.