Variable Prefixes


ColdFusion supports many different variable types, and when referring to variables the type may be specified as a prefix in the format prefix.variable. Many developers believe the best practice is to always use prefixes, but prefixes actually are not required in every instance. The following variables do not need to have a prefix:

  • Query result variables (if in a <cfoutput> loop)

  • Local variables

  • CGI variables

  • File variables

  • URL variables

  • FORM variables

  • COOKIE variables

  • CLIENT variables

NOTE

A variable's scope determines where it exists, how long it exists, and where its values are stored. The variable's prefix determines its scope.


Reason One to Use Prefixes: Performance

The first reason to use a variable prefix is performance. Consider a variable called TheVar that is used in an expression and not prefixed. ColdFusion must find the value for that variable. ColdFusion must look in each variable scope for the TheVar variable and its associated value. The closer the variable is to the bottom of the order of evaluation hierarchy, the longer it will take to retrieve the value of the variable.

TIP

For variable scopes that do not require prefixes, the order of evaluation is as follows:

  1. Query result variables (if in a <cfoutput> loop)

  2. Function local variables (with user defined functions and ColdFusion Component methods)

  3. ARGUMENTS (within a user-defined function or ColdFusion Component)

  4. Local variables

  5. CGI variables

  6. URL variables

  7. FORM variables

  8. COOKIE variables

  9. CLIENT variables


Reason Two to Use Prefixes: Avoiding Ambiguity

Problems can arise when the same variable name comes from two different scopes. Consider the following two assignment statements:

 <cfset TestVar="Local"> <cfcookie name="TestVar" value="Cookie"> 

The variable will be displayed using this statement:

 <cfoutput>#TestVar#</cfoutput> 

When evaluated, the value "Local" would be displayed. The COOKIE variable called TestVar is set after the local variable TestVar, but because of the order of evaluation, the local variable's value is displayed when the expression is evaluated. If you want to display the value of the COOKIE variable, you have to use the COOKIE prefix.

A Reason Not to Use Prefixes: Flexibility

Consider a template that is both the action page of a form and the target of a URL. A variable of the same name is passed in from each page. In this scenario, by not using a prefix, the template would work in both cases. The nonprefixed variable could act as both a FORM and URL variable.



Macromedia ColdFusion MX 7 Certified Developer Study Guide
Macromedia ColdFusion MX 7 Certified Developer Study Guide
ISBN: 0321330110
EAN: 2147483647
Year: 2004
Pages: 389
Authors: Ben Forta

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net