Var Scoping ColdFusion Tag-Specific Variables

I came across this issue during a code review, and thought it might be of note. Specifically, use of cfstoredproc. StatusCode inspired this.

You know that rule about var scoping all variables called in a function unless they are specifically needed elsewhere? Well don’t forget to do it to most of the “ColdFusion tag-specific variables.” They are:

  • cfdirectory
  • cffile
  • cfftp
  • cfhttp
  • cfindex
  • cfldap
  • cfpop
  • cfquery
  • cfregistry
  • cfsearch
  • cfstoredproc

Anything that returns a simple value (string, numeric, Boolean, numeric) or an even arrays and queries can be var scoped at the head of the function with an empty string. (Although for every type but query I like to initialize it with the correct data type.) Structs however have to be initialized with a StructNew().

I omit from the list:

  • cfcatch
  • cferror

CFcatch only exists during the execution of a cfcatch block and is accessible only by code in that block. In any case, my normal test for variable scope leakage doesn’t detect it, so I’m assuming it’s a special case. If anyone knows different please let me know. Likewise CFerror only exists in page referenced by a cferror tag, which probably couldn’t be in CFC call. (But I could be wrong.)

6 thoughts on “Var Scoping ColdFusion Tag-Specific Variables

  1. I could be way off here, but I could swear that I remember trying to “var” scope the CFFILE results:

    <cfset var CFFILE = “” />

    and it gave me some sort of error about dereferencing scalar objects as though they were structs with properties.

    Oh, and that makes me thinkg of something else… doesn’t ColdFusion create backwards compatable structures? I think for a CFFILE tag it creates both a CFFILE and a FILE structure. Do both need to be var’d? Hmmmm.

    Perhaps the best thing to do would be to use the “result” attribute for any tag that can take it and var that.

    I haven’t tested any of that though, so forgive me if I am misleading.

    Like

  2. I touched on this a bit in the post Ben, but I didn’t make it very clear. Structs needs to be initialized as structs. So it should be : <cfset cffile = StructNew() />. That would prevent the error.

    Like

  3. Terrence,

    Sorry, I think when I first read it, I didn’t quite understand what you were saying. I see. I read it too fast.

    Any thoughts on FILE vs. CFFILE?

    Excellent post by the way.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s