Version 1 (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.