(a) What cases should you var scope variables and (b) what cases should you not var scope in a ColdFusion components?
You should var scope your variables when you're implementing a function inside a CFC that is shared across multiple requests (i.e. Singleton, Service CFC's in Application scope)
You don't need to (yet still highly recommended to) var scope your variables if the CFC is instantiated every time, AND your method is not calling another method in the same CFC that may access the vars you've defined in the caller method. Such as a remote method that you called directly through web service or ajax, which doesn't call other methods that make use of vars you didn't var scope, or Controller in CFWheels.
"You should always define function-local variables using the var keyword." per CFC variables and scope doc http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=buildingComponents_29.html
You should var scope your variables any time you do not want the value of that variable to be affected by a) other requests accessing the same instance, or b) other methods within the same instance.
Henry is a great guy, but his statement that "You don't need to var scope your variables if the CFC is instantiated every time." is incorrect. :) [EDIT: Henry has since edited his answer] I wrote an example that illustrates this point in this blog entry:
http://daveshuck.com/2006/11/28/thread-safety-example-var-scope-your-loop-index-in-coldfusion-cfcs/
You can see that I created an infinite loop by counting up in one function and counting down in another. In this case it doesn't matter whether it is a singleton or multiple users requesting the same instance, but in a single request one function is overwriting the value in another function.
I var scope any variable that is not a global or member of the component. The last thing you want to be doing is creating or overwriting globals in the variables scope
We scope all vars in a function so that they stay local to that function only. As for the component, you can use variables or this scopes to make the variables available to any function in the component. The "this" scope will also make the variables directly available to the calling program if you set the access correctly.
© 2022 - 2024 — McMap. All rights reserved.