Yesterday someone emailed me asking about the assignCategory method of BlogCFC. Specifically, they wanted to know why I did this:
Where checkEC was defined as a query a few lines later. They noticed I did this throughout my code and were not sure why. I explained to them about how scoping works in UDFs. Any variable created in a UDF will automatically "leak" out of the UDF. (Note, when I say UDF, I also mean CFC method, as this applies to both.) This is easy enough to fix by using the VAR scope within your function.
However, you shouldn't forget that some tags act just like cfset. So for example, my cfquery tag creates a variable as well. By var scoping the name of the query, I ensure that the data doesn't escape the method.
So for most readers, this is old news, but it certainly can't hurt to repeat - as forgetting to var scope can lead to serious issues down the road.
Archived Comments
Thanks for tip. I figured it had something to do with localizing the var to the function but I was not aware that it could lead to issues down the road.
Thanks for your help Ray!
Ray,
Thanks for repeating this important tip. I think it would be nice in this context if we also mention the weird <cfinclude> functionality inside a cfc method. In a CFC method, if you include a file using cfinclude, it will essentially copy all the var scoped variables (previously declared for this function) to the variables scope of CFC.
I had this problem using the variable "i" in a loop in two functions that were called on the same page.. it took me /ages/ to figure out the problem. threw in a little "var i = 1" solved all of /those/ problems!
It's not just CFSETs but tags such as CFPARAM, which does not allow for the var. Very dangerous at times.
I would question why someone would use cfparam in a udf/method. If the intent is to say, define X if X isn't defined, then X should be an optional argument with default=...
People are people and will do strange things. Point is, any time a variable is created inside a methid/UDF, it 'should' be var-ed. CFPARAM is one of those variable creation tags that people forget about. What's needed is the ability to set per function or globally that a method/udf is 'protected' as in locally created vars are local, not global. I'd perfer this as default, but....
Good point.
Is:
<cfset var myVar = "">
the same as:
<cfset variables.myVar = "">
in the context of localizing variables within a ColdFusion component? Or can you comment on the differences, assuming you always access it as variables.myVar throughout the cfc?
Jason, no
Inside a method, cfset var x sets x to exist ONLY in the method. cfset variables.x makes x global to the entire cfc.