ColdFusion developers have long known to ensure that local variables remain local by using the “var” keyword to define them. Here’s an example:
In the above snippet, two variables are created. The first variable uses the var keyword to ensure that the variable is local to the function, and if the same variable name existed elsewhere it won’t be overwritten. The second variable does not use var, and as such is not local, and variable conflicts can indeed occur. And so, when creating user defined functions or ColdFusion Component methods, the rule has always been to always prefix local variables with “var”.
But what exactly is a var variable? What scope is it in? And how is it accessed using explicit scope notation? The answers to these questions are somewhat unclear, partially because the local var scope is not used like any other ColdFusion scope which is always designated by using a scope prefix (VARIABLES.myVariable, FORM.myVariable, SESSION.mayVariable, etc.).
ColdFusion Centaur simplifies the use of local scopes (without breaking existing code) by explicitly defining a local scope that it intuitively named LOCAL. Here is the same local variable set above, but using the LOCAL scope instead of var:
But what if you do indeed use var? Well, it’ll just work. Look at the following two
Both of these code snippets do the exact same thing. Variables with the var prefix are now automatically defined in the LOCAL scope. So a variable defined as:
can be safely accessed as:
It’s clean, it’s simple, it’s intuitive, and it’s fully backwards compatible. And yes, if you have a variable named “local” it’ll still work, the variable will just become LOCAL.local, and as the LOCAL scope is in the default evaluation chain it’ll just work.
Oh, one other change. The “var” keyword used to only be supported at the top of functions and methods, so all local variables had to be defined upfront. This limitation has been removed in ColdFusion Centaur (and I actually have mixed feelings about this, but so be it).