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]">
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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With