How do I avoid forgetting to declare local variables?
It is critical when writing component methods and UDFs that every variable defined in the code is properly var scoped. If you forget this step - the variable will exist outside of the method and could potentially lead to some very hard to debug problems. One way to get around accidentally forgetting to var scope is to create a structure for all the variables. Consider this code block:
<cfset var local = structNew() />
<cfset local.name = "Mickey Mouse" />
<cfloop index="local.i" from="1" to="10">
<cfoutput>#local.i#: #local.name#<br></cfoutput>
</cfloop>
In this example, the structure local was created to store all local variables. Notice that the rest of the code uses this structure for any variables created.
This question was written by Dale Fraser
It was last updated on November 13, 2006.