Ask a Jedi: Var Scoping Queries

Brian asks:

Your rantings about var scoping CFC function variables has really made me look closely to how I code. If I var scope the name of a query before querying a datasource, will that query object become local to the function as well?

Rant? Me? Ok - so maybe I go a bit off the deep end at times with var scoping. The main reason is that it makes stuff very hard to debug if something goes wrong. But to answer your question, yes, if you var scope the name of the query before you use it, it will keep the query local to the function. This is how I do it normally:

<cffunction name="foo" returnType='query" output="false" access="public"> <cfset var q = "">

&lt;cfquery name="q" datasource="kingsweallare"&gt;
select name from goo
&lt;/cfquery&gt;

&lt;cfreturn q&gt; &lt;/cffunction&gt; </code>

Notice that I did not define q as a query. Since CF is typeless, this is perfectly fine.

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