coldfusionscopecoldfusion-9

Scoping: Local vs Var


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?


Solution

  • 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.html

    Local will match only a variable in a local scope. Consider the following

    <cffunction name="himom">
        <cfoutput>
            <p><b>try 0:</b> #request_method#</p>
            <!--- you might think that the variable does not exist, 
                  but it does because it came from cgi scope --->
        </cfoutput> 
    
        <cfquery name="myData" datasource="Scorecard3">
            SELECT 'This is via query' AS request_method
        </cfquery>
        <!--- Data is now being loaded into a query --->
    
        <cfoutput query="myData">
            <p><b>try 1:</b> #request_method#</p>
        </cfoutput>
        <!--- This one now came from the query --->        
    
        <cfset var request_method = "This is Var">
        <!--- We now declare via var ---> 
     
        <cfoutput query="myData">
            <p><b>try 2:</b> #request_method#</p>
        </cfoutput> 
        <!--- the query version disappears and now 
              the var version takes precedence --->
    
        <cfset local.request_method = "This is local">
        <!--- now we declare via local --->
    
        <cfoutput query="myData">
            <p><b>try 3:</b> #request_method#</p>
        </cfoutput>
        <!--- The local method takes precedence --->
    
        <cfoutput>
            <p><b>try 4:</b> #request_method#</p>
            <!--- in fact it even takes precedence over the var --->
    
            <p><b>try 5:</b> #local.request_method#</p>
            <!--- there is no question where this comes from --->   
       </cfoutput>
    </cffunction>
    
    <cfset himom()>
    

    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 understood