Variables in CFML; Referencing Variable Scopes

All variables in ColdFusion are contained in a scope. Scopes can be thought of simply as predefined buckets of variables where each bucket serves a specific purpose. Standard scopes include "Form", "URL", "CGI" and many others. Understanding ColdFusion scopes is one of the most important concepts of ColdFusion development.

A variable within a scope is known as a member of that scope. The most common method of reference is Dot Notation as in ScopeName.VariableName like the following (both Dot Notation and the alternate, Indexed Notation are described fully later):

Form.FieldName
URL.Foo
CGI.SCRIPT_NAME

Each scope is separate from all others meaning that a scope can have variables named the same as variables in another scope without conflicting. For example the following lines create two completely separate variables:

<cfset Form.foo = "Hello">
<cfset URL.foo = "Goodbye">

Scopes and the methods for accessing them will be fully detailed later, for now it is enough to know that all variables are members of one or another scope.

Automatic Discovery

For many reasons it's recommended that you always specify the scope when using variables. This is known as scoping your variables. However if no scope is specified ColdFusion will search through the common scopes in the following specific order:

ColdFusion MX ColdFusion Pre-MX
  • Arguments
  • Variables (Local)
  • CGI
  • File
  • URL
  • Form
  • Cookie
  • Client
  • Variables (Local)
  • CGI
  • File
  • URL
  • Form
  • Cookie
  • Client

It should be obvious then than unexpected results can occur if you let ColdFusion discover the scopes of your variables when multiple scopes have variables of the same name. This is the main reason that you should always scope your variables. Scoping also improves code readability. The common exception to this rule is the Variables (or local) scope. As this is the default scope any unscoped variable will often be assumed to be a member of the Variables scope.

Scopes not on the above list (Server, Application, Session and Attributes among others) will not be discovered automatically. For these you must specify the scope. If you don't ColdFusion will attempt to find a match in the above scopes and if it fails an error will be thrown.

21 Current Sessions; Time: 14:56:51 06-01-2009; Tick: 625