Mohamad
Mohamad

Reputation: 35349

Is there a difference between declaring a variable in the LOC, VAR, and VARIABLES scopes?

I see all three notations used frequently, and I'm wondering what the differences are between them:

<cfset var foo = "bar" />
<cfset local.foo = "bar" />
<cfset variables.foo = "bar" />
<cfset arguments.foo = "bar" />

Upvotes: 2

Views: 3187

Answers (3)

Ciaran Archer
Ciaran Archer

Reputation: 12446

If you are wondering why use local over var in, for example, a CFC function, then consider these two examples:

<cffunction name="foo" returntype="query" output="false">

  <cfset var myQuery = "" />

  <cfquery name="myQuery">
    select * from bar
  </cfquery>

  <cfreturn myQuery />

</cffunction>

First you have to declare the variable as a var and then use it. Contrast with:

<cffunction name="foo" returntype="query" output="false">

  <cfquery name="local.myQuery">
    select * from bar
  </cfquery>

  <cfreturn local.myQuery />

</cffunction>

Essentially it cuts out all these var statements for loop variables and queries etc. One less line of code! :)

I hope that helps.

Upvotes: 3

DanSingerman
DanSingerman

Reputation: 36502

Firstly, I think you mean local scope, not loc (I am not aware of a scope called loc)

<cfset var foo = "bar" />
<cfset local.foo = "bar" />

Are supposed to be exactly the same. The variable will be private within the function it is defined in.

The variables scope, within a CFC, will create a variable private within an instance of the CFC (as opposed to the function)

Outside a CFC, I think the variables scope will be private whithin the template it is creataed in.

Upvotes: 1

Daniel Sellers
Daniel Sellers

Reputation: 750

var and local are the same scope and they are available only to the method/function in which they are declared. The local scope is new to CF 9 before that you used var to create variables that only existed in the method.

Variables is available to the entire cfc or cfm page in which they are declared and any included templates.

arguments is used for arguments passed into a method/function and only exists with in it.

Upvotes: 13

Related Questions