I have little impression about variables resolve order, but I can't find it in the CFML Reference or ColdFusion Dev Guide. Can anyone help?
Variables are a standard part of any programming language. A variable can be visualised as a container that stores a value. We can use variables in many circumstances.
CFML is dynamically typed, so types can change as required. You can see the current (JVM) type of a variable by doing <cfdump var=#getMetadata(var)# /> or simply by accessing getMetadata(var). getName() .
Local (function local) Contains variables that are declared inside a user-defined function or ColdFusion component method and exist only while a function executes. For more information, seeWriting and Calling User-Defined Functions. Request. Used to hold data that must be available for the duration of one HTTP request.
The canonical scope order for ColdFusion 9 is:
You can see Adobe's documentation on this in Developing ColdFusion 9 Applications.
However, some scopes are only available in certain contexts, so the order that scopes are searched is different, depending upon the context of the code.
As Al Everett notes in his answer, it is considered best practice to always scope variables. Explicit scoping produces less ambiguous code and is usually faster. Anytime you don't scope a variable, you risk getting a variable from a scope that you didn't intend to.
When the variable you are accessing is in the first scope in the search order, it is actually slightly faster to leave the variable un-scoped. This is because each dot in a variable name incurs a small cost as ColdFusion resolves it. For example, in a CFC method it is slightly faster to access
myVar
thanlocal.myVar
. This only applies to:
local
scoped variables inside a CFC or UDF- Thread
local
scoped variables inside a threadvariables
scoped variables inside CFMLIn all other circumstances it is faster (and clearer) to explicitly declare the scope.
Use of this technique should be considered bad practice. You should only use this technique in performance-critical code, where you can guarantee that the variable always exists in the intended scope. Keep in mind that it comes at the cost of increased ambiguity.
It is a generally accepted best practice to always scope your variables for two main reasons:
That said, here's the order variable scopes are searched:
EDIT: It's also telling to note what scopes are not searched: SESSION, SERVER, APPLICATION
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With