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?
问题:
回答1:
It is a generally accepted best practice to always scope your variables for two main reasons:
- Performance - CF doesn't need to find the variable by searching through the scopes in turn
- Accuracy - if two variables have the same name in different scopes, you may not get the one you were expecting
That said, here's the order variable scopes are searched:
- Function local (VAR keyword)
- Thread local (CFTHREAD)
- Query results
- Function ARGUMENTS
- Local VARIABLES
- CGI variables
- FILE variables
- URL parameters
- FORM fields
- COOKIE values
- CLIENT variables
EDIT: It's also telling to note what scopes are not searched: SESSION, SERVER, APPLICATION
回答2:
Scope Order
The canonical scope order for ColdFusion 9 is:
- Local (only inside CFCs and UDFs)
- Arguments (only inside CFCs and UDFs)
- Thread local (only inside threads)
- Query (only inside a query loop)
- Thread (only inside threads and templates that call threads)
- Variables
- CGI
- Cffile
- URL
- Form
- Cookie
- Client
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.
Inside CFML (no threads)
- Variables
- CGI
- Cffile
- URL
- Form
- Cookie
- Client
Inside a CFC (no threads)
- Local
- Arguments
- Query (only inside a query loop)
- Variables
- CGI
- Cffile
- URL
- Form
- Cookie
- Client
Best Practice
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.