ColdFusion: variables, scopes and their ordering

In ColdFusion, it is generally a good idea to prefix your variables.

Why?  Performance and Ambiguity.

Performance

If you set a variable and then tried to output it:

<cfset myvariable = “my value”>
<cfoutput>#myvariable#</cfoutput>

ColdFusion will look into each scope until it finds the variable.

ColdFusion searches for variables without a scope the following order:

  1. Query result (in a <cfoutput> loop)
  2. Arguments (within a function or CFC)
  3. variables (local)
  4. CGI
  5. URL
  6. FORM
  7. COOKIE
  8. CLIENT

Ambiguity

If you set a variable the following way and output:

<cfset myvariable = “local variables scope”>
<cfcookie name=”myvariable” value=”cookie scope”>
<cfoutput>#myvariable#</cfoutput>

The result would be: “local variables scope”

This is because ColdFusion searched the scopes in order until it reached the local variables scope.

Both variables still exist and are accessible by using the scope prefix.

<cfoutput>
#variables.myvariable#<br />
#cookie.myvariable#
</cfoutput>

The result would be:

local variables scope
cookie scope

Advertisement

One Response

  1. Good post. My most recent issue came when a previous code did not scope variables in an application.cfm file. So when moving to an application.cfc file, I had to go through the entire site, do a search and replace on the current variables, and add the scope – application or request. It wasn’t much of a hassle, but could have been avoided.

    Definitely scope all variables for efficiency, readability, and other coder’s usability!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.