Ask a Jedi: Variables versus Var in a CFC
Nick asks:
Quick question: is there any difference between using <cfset variables.databasename = "" /> and <cfset var databasename = "" /> in a CFC?
It makes a big difference. A CFC, like a 'normal' CFM page, has a Variables scope. Inside a CFC, a variable in the Variables scope is accessible anywhere. So, as a typical example, one may use Variables.DSN throughout a CFC to retrieve a datasource variable. Here is some quick pseudo-code showing an example of setting the variable in the init() function then using it later. Again - this is pseudo-code and I haven't had a full cup of coffee yet:
<cfcomponent>
<cfset variables.dsn = "">
<cffunction name="init">
<cfargument name="dsn" type="string" required="true">
<cfset variables.dsn = arguments.dsn>
<cfreturn this>
</cffunction>
<cffunction name="fixMyXBox">
<cfset var q = "">
<cfquery name="q" datasource="#variables.dsn#">
select .....
</cfquery>
<cfreturn q>
</cffunction>
</cfccmponent>
A var scope variable, however, only exists for the execution of the method. Look in my example above at the fixMyXBox method. That method creates one variable, a query, so I use the var scope to keep it local to the method itself. Once the method ends, q will no longer exist, but variables.dsn will stick around. (To be clear, it will stick around if you are calling more methods in the same instance of the CFC. But I think you get my point.)
Comments
Let me rewrite that. Just never, ever, leave the scope off of Variables values. Always specify it. The only unscoped vars should be local variables.
i use this var method like you preach, have since i got a preaching sometime ago, years maybe. anyway, when working with that method, or function i feel weird not having a "something." in front of it, like its an unscoped variable, and i could maybe duplicate names or something, it just feels odd. anyway, does this have a prefix?
later
sometimes in like spur of the moment game programming i might forget to, but i do not think there are any cases where i do not use a scoped variable, EVER, i find it in legacy code all the time, but i just fix and go on.
its funny to look back at old code and see instances of too many and WHOLLY not needed #'s all over the place.
anyway, ok, so im not the only one on this... nice.
I always use the 'variables' prefix to scope variables, even outside CFCs.
In CFCs methods (and UDFs), I always use local scoped variables when I don't need to retain the value.
I usually create a local scoped structure to hold them, e.g.:
<cfscript>
var local = structNew();
local.myVar1 = ...
local.myVar2 = ...
</cfscript>
That way you recognize local scoped variables very easily.
I borrowed this technique from a Fusebox sample application and it worked fine for me so far.
What do you think about it?
Thanks.

