Ask a Jedi: CFC Scope Question

Jason asks:

I know it is important to ALWAYS var scope your variables in your CFCs my question is, is there a difference between these two cfset statements? <cfset var myVar = "" />

<cfset variables.myVar = "" />

It is indeed very important, and there is a world of difference between those two lines of code. I cover this more in my CFC Scope Reference, but the basic difference is that your first line of code creates a variable that will only exist for the execution of the method. You use this for any variable you create in the method, and be sure to not forget things like loop counters, query names, etc.

The second line creates a global variable the CFC. Anything in the variables scope is available to every method of the CFC. I’ll typically use the variables scope for configuration information, like a DSN, so all my queries will use datasource=”#variables.dsn#”. You would definitely not want to use it for things you intend to just be in the local method.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments