Search code examples
coldfusioncoldfusion-11

ColdFusion 11: Difference between setting a variable with a #Evaluate# in a <CFSET> tag


Working on a legacy ColdFusion application, I have encountered a mismatch in how the <cfset> tag is used throughout the application. The same variable is set with the evaluation operator # # and without

I have encountered this on the application scope

<cfset #application.test# = "test">
<cfset application.test = "test2">

And the on variable scope ...

<cfset myvariable = 6> 
<cfset #myvariable# = 5>

After doing a

<cfdump var=#variables#>
<cfdump var=#application#>



test        == "test2" 
myvariable  == 5

so it does seems they reference the same variables.

I was wondering if there are any best practices/ edge cases/ things happening behind the scene that I need to be mindful of ... or is the evaluation operator not doing much in this case?

(Does scoping of the variable matter?)


Solution

  • The pounds # tell the CFML parser to evaluate the term surrounded with them, useful in strings. They are required if you pass variables in tag attributes such as <cfloop array="#myArray#"... or want to avoid string concatenation as in "Hello #name#!" or need dynamic expressions such as <cfargument name="datetime" default="#now()#">. The pounds in your examples do nothing and do not affect performance. It is considered bad practise to use pounds when not needed though.

    Scoping does matter. Some scopes are (partially) persistent (application, request, session), others are volatile (variables, local). It depends on the context. variables in a cfcomponent is a private instance field scope while variables in a .cfm template works like a local variable. To have local variables in a function, the var keyword or the local scope is used. Have a look at the official documentation about all the scopes.

    You should specify the scope because ColdFusion attempts to find the variable whenever you omit the scope by searching through a set of scopes and picking the first one with the matching name. This has performance overhead (almost negligible though) and can lead to strange issues because of bleeding variables. Some people (me included) don't specify variables outside of a cfcomponent, because it's the default scope. That's up to you.