Ask a Jedi: Variables versus Var in a CFC

Nick asks:

Quick question: is there any difference between using <cfset variables.databasename = "" /> and <cfset var databasename = "" /> in a CFC?

It makes a big difference. A CFC, like a ‘normal’ CFM page, has a Variables scope. Inside a CFC, a variable in the Variables scope is accessible anywhere. So, as a typical example, one may use Variables.DSN throughout a CFC to retrieve a datasource variable. Here is some quick pseudo-code showing an example of setting the variable in the init() function then using it later. Again - this is pseudo-code and I haven’t had a full cup of coffee yet:

<cfcomponent>

<cfset variables.dsn = ““>

<cffunction name=”init”> <cfargument name=”dsn” type=”string” required=”true”>

<cfset variables.dsn = arguments.dsn>

<cfreturn this> </cffunction>

<cffunction name=”fixMyXBox”> <cfset var q = ““>

<cfquery name=”q” datasource=”#variables.dsn#”> select ….. </cfquery>

<cfreturn q> </cffunction>

</cfccmponent> </code>

A var scope variable, however, only exists for the execution of the method. Look in my example above at the fixMyXBox method. That method creates one variable, a query, so I use the var scope to keep it local to the method itself. Once the method ends, q will no longer exist, but variables.dsn will stick around. (To be clear, it will stick around if you are calling more methods in the same instance of the CFC. But I think you get my point.)

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