Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

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 at 3:12:09 PM EST.

CFML Referenced

StructNew()
<cfoutput>
<cfloop>

Categories

Components

Comments

Comment made by Tony Petruzzi on November 24, 2006 at 10:00 PM
Just a reminder that the word Local is a reserved word in a cfquery. So if you follow this advice and want to use query of queries within your function, you will have to wrap the word local within [] in order to avoid erros.

For instance:

<cfquery name="test" dbtype="query"> SELECT * FROM [local].myquery </cfquery>


Comment made by ArdMan on February 25, 2009 at 10:10 AM
Instead of using the variable named "local", I have been using "lcl". It has worked out great.