| Version 2 (modified by anonymous, 15 years ago) |
|---|
Some developers occasionally note variables present in controller objects are shared across user requests. The reason for this is a developer misunderstanding in how ColdFusion? variables coexist in CFCs and also in how Model Glue controllers operate.
Model Glue controllers are created once, when the Model Glue application initializes. The Controller instances are kept in memory as long as the application is alive. Since these controller objects are cached, in effect, all memory variables internal to a controller are also cached.
The reason why some variables can occasionally slip across requests is because of the way ColdFusion? handles variables inside functions. Unless a variable is created with the "var" keyword, the variable is global to all functions in a controller. This is the root cause why some variables cross user requests.
The "var" keyword is the proper way to create any variable local to a controller function ( and not intended to apply to all functions/scopes in a controller object.
Rather than:
<cfset age = 5 />
You should create variables in controller objects like this:
<cfset 'var' age = 5 />
This generally applies to all variables created in all CFCs for best practice. You do not need to use the "var" keyword inside .cfm pages or in Model Glue views, as there is no scope boundaries to accidentally cross. Remember, using the "var" keyword on a variable inside a function body ensures that the variable only exists for that execution of the function. The variable is discarded after the function execution completes.
If you need help finding areas in your code that need the "var" keyword added, download the Varscoper tool. The Varscoper tool will scan all of your code and report back the lines that need the "var" keyword added.
A Note on ColdFusion 9 (text borrowed from Ray Camden's site)
You must still continue to var scope your variables in UDFs and CFC methods. There is no change in this respect. ColdFusion 9 only makes two related changes:
- The var scope previous was an "unnamed" scope. ColdFusion? 9 fixes this by creating a scope called 'local'. Like other ColdFusion scopes you can treat this as a structure.
- Because there is an implicit local scope, you can now skip the var keyword and use "local." instead:
- CF8 and older: var myVar1=1
- CF9: local.myVar1=1
![(please configure the [header_logo] section in trac.ini)](/ModelGlue.com/trac.cgi/chrome/site/your_project_logo.png)