Scope

We all start out learning ColdFusion by outputing variables using CFOUTPUT and some pound signs. A variable with an name like myvariable was passed to the page by a form or a link and output as #myvariable#. By not understanding and using scope, we unwittingly add inefficiencies to our code and overlook a lot of advantages that come with using scopes.



So what is scope? A scope is a group where related variables exist. As an example when you submit a form, ColdFusion finds all of the submitted data in the form scope. If you ask ColdFusion to use a variable described in web address like www.mysite.com/index.cfm?fuseaction=article, it will find it in the URL scope.

When we call on a variable without a scope, ColdFusion searches through all scopes to find the variable.By scoping the variables we can speed up the rendering of our pages and minimize coding errors. Without scoping there is a chance that we may have two variables of the same name and ColdFusion will display the first one it finds, not the one you were looking to dispay. To output a scoped variable, we place the scope name infront of the variable with a "dot" notation such as #form.password#.

There are several scopes that do not require that the scope be called out. When CF sees a variable, it searches through the following scopes in order and presents the first occurance of the variable. If URL.userid and Client.userid exist, #userid# will display the value of URL.userid. The scopes that CF searches through are:


QUERY the results of a query you created using CFQUERY, CFDIRECTORY, CFLDAP, CFPOP or a custom tag
ARGUMENTS As passed into a User Defined Function (UDF) or ColdFusion Component (CFC)
Local Variables Local variables you create with CFSET
CGI Variables passed from the webserver
URL Variables passed with the URL like http://www.cfnewbie.com?fuseaction=list
FORM Variables passed as fields from a form
COOKIE Variables available from cookies set by CFCOOKIE or Javascript
CLIENT Variables available from a particular computer that were set by CFSET.

A great way to see available variables in a scope when using ColdFusion MX is to use CFDUMP. CFDUMP will dump all keys and values of variables



More CFNewbie?com Articles

 

CFNewbie?com