Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the var keyword in coldfusion and how many times to use it

I always try to make use of the var keyword when inside functions using CF, but one probably stupid question I have is, how often do you have to use it ?

Example :

<cfset var local = ""> <!-- set at the top of the function -->

<!-- then later in the function -->
<cfset var local.firstname = "steve">
<cfset var local.lastname = "smith">
<cfset var local.email = "[email protected]">

is it a case of every time you write a variable you have to set the keyword, or just the first instance of it when used within a function ?

Or is it just the same as

<cfset var local = ""> <!-- set at the top of the function -->

<!-- then later in the function -->
<cfset local.firstname = "steve">
<cfset local.lastname = "smith">
<cfset local.email = "[email protected]">
like image 488
user125264 Avatar asked Nov 01 '15 06:11

user125264


2 Answers

Which version of ColdFusion are you using? Since ColdFusion 9 local is a scope, so there's no point in specifically creating it.

To answer your question: all function-local variables need to be actively made local to the function. ColdFusion does not do this automatically.

There's two ways of doing this. Via the var keyword:

var someVar = someValue;

Or via the local scope:

local.someVar = someValue;

You are confused in your examples as to what a variable is. Given this code:

var myStruct = {};
myStruct.someKey = "some value";

In this examply myStruct is the variable. myStruct.someKey is not a discrete variable, it's merely a subkey of the myStruct variable. So this doesn't make sense:

var myStruct = {};
var myStruct.someKey = "some value";
like image 137
Adam Cameron Avatar answered Sep 24 '22 16:09

Adam Cameron


You do not need to use the 'var' keyword for variables that are in the 'local' scope. Since 'local' is a structure all its members are part of the same scope.

Basically the 'local' struct is just a container to hold all variables that must be in the function's local scope.

UPDATE: AS of CF9 local is an explicit scope that you use to hold your function scoped variables, without declaring it. Usually I type it uppercase but that's a matter of taste.

<cfset LOCAL.firstname = "steve">
<cfset LOCAL.lastname = "smith">
<cfset LOCAL.email = "[email protected]">

In Coldfusion 8 and before you would typically define a local struct at the top of your function:

<cfset var LOCAL = structNew() />

However you could choose any other name for that struct.

like image 41
Richard Osseweyer Avatar answered Sep 22 '22 16:09

Richard Osseweyer