In ColdFusion, variables are resolved in what orde

2019-01-14 18:32发布

问题:

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:

  1. Function local (VAR keyword)
  2. Thread local (CFTHREAD)
  3. Query results
  4. Function ARGUMENTS
  5. Local VARIABLES
  6. CGI variables
  7. FILE variables
  8. URL parameters
  9. FORM fields
  10. COOKIE values
  11. 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:

  1. Local (only inside CFCs and UDFs)
  2. Arguments (only inside CFCs and UDFs)
  3. Thread local (only inside threads)
  4. Query (only inside a query loop)
  5. Thread (only inside threads and templates that call threads)
  6. Variables
  7. CGI
  8. Cffile
  9. URL
  10. Form
  11. Cookie
  12. 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)

  1. Variables
  2. CGI
  3. Cffile
  4. URL
  5. Form
  6. Cookie
  7. Client

Inside a CFC (no threads)

  1. Local
  2. Arguments
  3. Query (only inside a query loop)
  4. Variables
  5. CGI
  6. Cffile
  7. URL
  8. Form
  9. Cookie
  10. 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 than local.myVar. This only applies to:

  • local scoped variables inside a CFC or UDF
  • Thread local scoped variables inside a thread
  • variables scoped variables inside CFML

In 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.