Search code examples
coldfusionevaluate

Coldfusion syntax - how to use Evaluate


I'm trying to determine if a variable with a variable name is defined. Please help with my syntax... my attempts so far:

<cfif isDefined(Evaluate("session['#url.sessionSQL#']['SQL_ALL']"))>

<cfif isDefined('Evaluate("session[#url.sessionSQL#]")["SQL_ALL"]')>

<cfif isDefined(Evaluate("session['#url.sessionSQL#']['SQL_ALL']"))>        

<cfif isDefined('session[Evaluate("#url.sessionSQL#")]["SQL_ALL"]')>

<cfif isDefined('session["#url.sessionSQL#"]["SQL_ALL"]')>

Thanks.


Solution

  • Your question is a little confusing ;)

    If session[url.sessionSQL]['SQL_ALL'] contains the name of a variable, you can use structKeyExists to verify that variable exists in a particular scope.

    <cfif structKeyExists(scopeToCheck, "TestForThisVariableName")>  
    ... ie
    <cfif structKeyExists(variables, session[url.sessionSQL].SQL_ALL)>
    

    On the other hand, if just want to verify those session variables exist

      <cfif structKeyExists(session, url.sessionSQL) AND 
            structKeyExists(session[url.sessionSQL], "SQL_ALL")>
    

    Either way, you do not need the evaluate() function.

    Update: From comments, a key difference between IsDefined and StructKeyExists is precision. IsDefined examines a whole list of scopes when deteriming if a variable exists. Usually (though not always) that is undesirable because it can lead to unexpected results if you forget a particular variable exists in multiple scopes. (Using IsDefined inside a function is a prime example.) When you specifically want to check multiple scopes, then IsDefined() is more appropriate. Otherwise, I would stick with StructKeyExists as its results are less ambiguous.