ColdFusion Tips & Tricks: Components

ColdFusion Components and Var Scoping Trick

Var scoping is essential when dealing with ColdFusion Components. You can get weird results or even some hard-to-track errors if you don't do this. I'm not privy as to why this happens, I just know that it does. It's one of those mysteries that I just never bothered to research. All I know, is that sometimes it's a pain in the butt, especially when your writing a fairly complex function and you forgot to var scope an "i" in a cfloop or some other quick and dirty variable you made.

Well a few months back, I started doing something with my function variables, that I thought I would share. Not only does it solve my var problem, but it winds up making the top of my function shorter (I'm a stickler for cleanish looking code). Essentially I create a generic local struct in the begining and I'm sure to var scope it, like so:

<cfset var local = StructNew() />

And then as I begin writing my function, I just ad variables to the struct. So if I need to add a loop counter, I would just declare it like this:

<cfloop index="local.i" from="0" to="10">

   ...my fun loop stuff...

</cfloop>

Need to declare and array? No problem:

<cfset local.my_array = ArrayNew(1) />

This has really been a time saver for me and I no longer worry about var scoping my variables. At first, I didn't realize how easy this made my function writing life, but now it's just an automatic process that I don't even think about. If anyone knows a reason as to why I shouldn't do this, please let me know. But until then I'm not stopping!

Hope you find this useful.

Have something to say? Leave a comment!

You don't have to be registered to leave a comment. Unregistered user's comments will be approved before going live.




You are currently posting as an unregistered user.
This means that your comment will be reviewed prior to going live. If you are a registered user, please . New user? No problem, register for an account, it's FREE! Benefits include, posting instantly, screen name protection, collaboration recognition, subscribe to article updates, and so much more!