CF9 introduces LOCAL scope

ColdFusion 9 is coming and quite some neat new features are being presented to the audience. One of those things is the newly introduced LOCAL scope. This has, however, caused a little stir on Ben Forta’s blog post, as it raises some questions.

The creators of ColdFusion decided that variables in functions should, by default, be stored in the VARIABLES scope and thus are global. This means that any variable you create inside a function that happen to have a name also used outside that function will overwrite the value outside that function. Here’s an example.

<cffunction name="myFunction" returntype="void">
	<cfset foo = "adobe">
</cffunction>
 
<cfset foo = "bar">
<cfoutput>#foo#</cfoutput> <!--- Outputs "bar" --->
 
<cfset myFunction()>
<cfoutput>#foo#</cfoutput> <!--- Outputs "adobe" --->

So, as you can see this might lead to some unexpected results, especially when dealing with multiple files and large applications. We have the keyword “var” for declaring variables locally, but the drawback is that each and every variable has to be declared in the function before anything else. Therefore we use a little trick:

<cffunction name="myFunction" returntype="void">
	<cfset var local = structnew()>
	<cfset local.foo = "adobe">
</cffunction>
 
<cfset foo = "bar">
<cfoutput>#foo#</cfoutput> <!--- Outputs "bar" --->
 
<cfset myFunction()>
<cfoutput>#foo#</cfoutput> <!--- Outputs "bar" --->

In ColdFusion 9, Adobe introduces the LOCAL scope. This basically means that all variables created inside a function are by default private. This is a huge step forward if you ask me, since we now don’t have to remember to create a private structure on the start of every single function.

It, however, also led to some confusion, as people – and I was one of them – are wondering how their current code would evaluate, code that uses the trick mentioned above. The great thing is that, the way I understand it, we shouldn’t really notice the LOCAL scope anywhere, unless we force it. This means that in the second example we would have LOCAL.local.foo = “bar”. When we do require direct control over the LOCAL scope, we will have to use the Struct functions.

We have a testserver at work on which I’ll run some tests to see if it really works as expected. To be continued.

Leave a reply