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:
- Query result (in a <cfoutput> loop)
- Arguments (within a function or CFC)
- variables (local)
- CGI
- URL
- FORM
- COOKIE
- 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
Filed under: ColdFusion | Tagged: cf, ColdFusion, scopes, search order, variables
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!