I'm new to CF so this may be a basic question. But I've heard I should use local for objects inside functions due to how scoping works in CF. But what about 'var'? Is var the same as using local?
e.g.
function MyFunction()
{
local.obj = {};
}
Is this the same as:
function MyFunction()
{
var obj = {};
}
If they aren't the same, what is the difference between them? And when should I be using either of them?
They are very similar, but not exactly the same. Both only exist inside of a function but they work slightly differently.
The
var
version works it way through all the default variable scopes. See http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec09af4-7fdf.htmlLocal will match only a variable in a local scope. Consider the following
Results of the above
try 0: GET
try 1: This is via query
try 2: This is Var
try 3: This is local
try 4: This is local
try 5: This is local
In summary
When developing, you could use either to make sure that variables only exist inside of a function, but always prefixing your variables with
local
goes a long way in making sure that your code is clearly understoodIn ColdFusion 9+, using the local scope and the var directive in a ColdFusion CFC provide the same result.
Ben Forta explains it here: http://forta.com/blog/index.cfm/2009/6/21/The-New-ColdFusion-LOCAL-Scope
I would recommend using the local. notation as it is more explicit.