In Coldfusion, all variables are global by default, unless they are declared with the var
keyword. (Somewhat similar to the situation in Javascript.)
So you either have to remember to var
every variable used in a function, including things like names that are using in a cfquery
name
, or you can just use this trick:
<cffunction name="MyFunction">
<cfset var Local = StructNew()>
<!--- Now anything Local. is automatically local --->
<cfset Local.x = 42>
<!--- Including cfquery name="" --->
<cfquery name="Local.Customers" datasource="some_datasource">
SELECT C.ID, C.Name
FROM Customers C
</cfquery>
</cffunction>
There's nothing magic about the name Local
, it's just convention. Although Coldfusion 9 will add an explict local scope, so if you use Local
it will probably ease upgrading to CF9 when the time comes.
Note that the situation is a tad different for CFCs: In CFCs, the variables
scope (the "default" scope) isn't global like it is for normal functions but rather exists per instance of your CFC. So while forgetting to use var
is not quite as dangerous in a CFC as it is in a top-level function, the best practice is still to use var
all the time.