Skip to main content
April 13, 2012
Answered

Var name as string

  • April 13, 2012
  • 5 replies
  • 3970 views

Hi,

I'm new to cold fusion and i'd like to know how can i get a variable name to a string or other variable...

I want to declare a variable:

myvar = "contents";

and dinamically create an ouput like this: "the value of myvar is "contents""

Thanks

    This topic has been closed for replies.
    Correct answer Adam Cameron.

    Hi Rockit8.

    I know you've worked around your issue (I'd still like to know exactly what it was you needed to do), but I think I have worked out kinda what you were asking, and to quench my curiousity, I want to follow this up some more to clarify some things (for me, and possibly for you).

    I suspect what you're asking is demonstrated by this pseudocode:

    <cffunction name="myFunction">

              <cfargument name="theArgumentFromThePerspectiveOfTheFunction">

              <!---I have arguments.theArgumentFromThePerspectiveOfTheFunction, but I want to know that it got its value from variables.theVariableWhoseNameIWantToKnow --->

              <cfreturn somehow("variables.theVariableWhoseNameIWantToKnow")>

    </cffunction>

    <cfset variables.theVariableWhoseNameIWantToKnow = "some value">

    <cfset variables.theNameOfTheVariable = myFunction(variables.theVariableWhoseNameIWantToKnow)>

    Is that the sort of thing you're wanting to do?  This is not possible.

    When calling a function like this, the function never knows anything about variables.theVariableWhoseNameIWantToKnow, it never gets passed variables.theVariableWhoseNameIWantToKnow, it just gets passed its value.  And CF puts the value into arguments.theArgumentFromThePerspectiveOfTheFunction.  The only variable myFunction() knows about is arguments.theArgumentFromThePerspectiveOfTheFunction.  It is irrelevant to myFunction() that the calling code used a variable to hold "some value", it could just as likely have been:

    <cfset variables.theNameOfTheVariable = myFunction("some value")>

    This demonstrates why I say your question - as asked - is meaningless.

    However not all data is passed by value.  Consider this code:

    <cfset variables.firstOneToReferenceTheStruct = {foo="bar"}>

    <cfset variables.anotherOneThatReferencesTheStruct = variables.firstOneToReferenceTheStruct>

    In CF, a struct is copied by reference (kinda), not value, so both variables.firstOneToReferenceTheStruct and variables.anotherOneThatReferencesTheStruct will be separate references to the same piece of memory (and the memory holds the struct {foo="bar"}.

    So if one has this code:

    <cfset variables.theNameOfTheVariable = myFunction(variables.anotherOneThatReferencesTheStruct)>

    Then arguments.theArgumentFromThePerspectiveOfTheFunction will simply be yet another reference to exactly the same memory as variables.firstOneToReferenceTheStruct and variables.anotherOneThatReferencesTheStruct.  So one might initially think "aha, so there's a way to know that arguments.theArgumentFromThePerspectiveOfTheFunction was 'originally' called 'variables.firstOneToReferenceTheStruct'".  No, there isn't.  Because whilst those references all point to the same memory, they're all still completely separate references (a reference is a memory address, so each of those three actually just hold the memory address that the struct is at, but it's three separate copies of the address.  Not three separate copies of the content of the memory address, but three separate copies of the address), and do not have any corelation at all.

    Now... Java obviously keeps track of which references point to which bits of memory (so it knows when memory can be cleared by the garbage collector), so it is possible to find out a list of references that reference that particular piece of memory, but I don't know that this is exposed even via the Java API, and it's definitely not exposed to ColdFusion. I'm not a Java developer, but I can google, but I did not come up with any Java functionality that exposes this (disclosure: I only spent about 2min trying).  I suspect it's too low level, and not really of any particular use.  Why really would one want to know this sort of thing anyhow?  It's not useful information to an application, after all.

    Does this explain why I said your question is a bit meaningless?

    --

    Adam

    5 replies

    Adam Cameron.Correct answer
    Inspiring
    April 14, 2012

    Hi Rockit8.

    I know you've worked around your issue (I'd still like to know exactly what it was you needed to do), but I think I have worked out kinda what you were asking, and to quench my curiousity, I want to follow this up some more to clarify some things (for me, and possibly for you).

    I suspect what you're asking is demonstrated by this pseudocode:

    <cffunction name="myFunction">

              <cfargument name="theArgumentFromThePerspectiveOfTheFunction">

              <!---I have arguments.theArgumentFromThePerspectiveOfTheFunction, but I want to know that it got its value from variables.theVariableWhoseNameIWantToKnow --->

              <cfreturn somehow("variables.theVariableWhoseNameIWantToKnow")>

    </cffunction>

    <cfset variables.theVariableWhoseNameIWantToKnow = "some value">

    <cfset variables.theNameOfTheVariable = myFunction(variables.theVariableWhoseNameIWantToKnow)>

    Is that the sort of thing you're wanting to do?  This is not possible.

    When calling a function like this, the function never knows anything about variables.theVariableWhoseNameIWantToKnow, it never gets passed variables.theVariableWhoseNameIWantToKnow, it just gets passed its value.  And CF puts the value into arguments.theArgumentFromThePerspectiveOfTheFunction.  The only variable myFunction() knows about is arguments.theArgumentFromThePerspectiveOfTheFunction.  It is irrelevant to myFunction() that the calling code used a variable to hold "some value", it could just as likely have been:

    <cfset variables.theNameOfTheVariable = myFunction("some value")>

    This demonstrates why I say your question - as asked - is meaningless.

    However not all data is passed by value.  Consider this code:

    <cfset variables.firstOneToReferenceTheStruct = {foo="bar"}>

    <cfset variables.anotherOneThatReferencesTheStruct = variables.firstOneToReferenceTheStruct>

    In CF, a struct is copied by reference (kinda), not value, so both variables.firstOneToReferenceTheStruct and variables.anotherOneThatReferencesTheStruct will be separate references to the same piece of memory (and the memory holds the struct {foo="bar"}.

    So if one has this code:

    <cfset variables.theNameOfTheVariable = myFunction(variables.anotherOneThatReferencesTheStruct)>

    Then arguments.theArgumentFromThePerspectiveOfTheFunction will simply be yet another reference to exactly the same memory as variables.firstOneToReferenceTheStruct and variables.anotherOneThatReferencesTheStruct.  So one might initially think "aha, so there's a way to know that arguments.theArgumentFromThePerspectiveOfTheFunction was 'originally' called 'variables.firstOneToReferenceTheStruct'".  No, there isn't.  Because whilst those references all point to the same memory, they're all still completely separate references (a reference is a memory address, so each of those three actually just hold the memory address that the struct is at, but it's three separate copies of the address.  Not three separate copies of the content of the memory address, but three separate copies of the address), and do not have any corelation at all.

    Now... Java obviously keeps track of which references point to which bits of memory (so it knows when memory can be cleared by the garbage collector), so it is possible to find out a list of references that reference that particular piece of memory, but I don't know that this is exposed even via the Java API, and it's definitely not exposed to ColdFusion. I'm not a Java developer, but I can google, but I did not come up with any Java functionality that exposes this (disclosure: I only spent about 2min trying).  I suspect it's too low level, and not really of any particular use.  Why really would one want to know this sort of thing anyhow?  It's not useful information to an application, after all.

    Does this explain why I said your question is a bit meaningless?

    --

    Adam

    April 16, 2012

    Adam, thanks for your reply.

    What you described was equivalent to what i wanted to do in the first place, but just to clarify i will explain it here.

    I had to develop a custom tag where i would receive a coldfusion array, and return a structure with a property with the name of that array...so i somehow needed to know the name of the array inside my custom tag.

    After reading the replys in this discussion i came to the conclusion that what i was asking might not be possible to do, so i worked my way around it by receiving the name of that array as an argument.

    Thanks and regards.

    Participant
    April 13, 2012

    @Rockit8, first of all, welcome to the ColdFusion Community, don't hesitate to ask any question on this forum or on Twitter using the hashtag #ColdFusion.  Our community is full of great folks ready to lend a hand.

    Here's an example you can do to dynamically extract the information you want, keep in mind that all variables in coldfusion are set within a scope, for example, if you set on a .cfm page:

    myVariable = "myValue";

    The myVariable is being set on the VARIABLES scope.  meaning it's now VARIABLES.myVariable.  If you think in these terms you'll probably come to the realization that you can search the appropriate scope and extract the piece of information you need, here's an example for your problem:

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

      /**

        * searches scopes for a variable's name and value, returns a struct with variable's name and value

        * scope default to variables, you can pass an array of the scopes you want to search for given variable

        * first found occurrence is returned

       */

      public Struct function getSimpleVariableStats(required any simpleVar, array searchScopes=[variables]){

        // search across all passed scopes

        for(var scope in arguments.searchScopes)

        {

          // search across current scope's keys

          var scopeKeys = listToArray(structKeyList(scope));

          for(var scopeKey in scopeKeys){

            // if value is simple and found, return stats

            if(isSimpleValue(scope[scopeKey]) && scope[scopeKey] == arguments.simpleVar){

              return {

                "variableName" = scopeKey,

                "value" = scope[scopeKey]

              };

            }

          }

        }

      }

      // your variable

      someVariable = "someValue";

      // get variable stats (see function above)

      varStats = getSimpleVariableStats(someVariable);

     

      // output your string with variable stats

      writeOutput("The value of " & varStats.variableName & " is " & varStats.value);

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Hope this helps you, and best of luck.. like Andy said this forum is here to help anyone.  Hope to see you around!

    Cheers..

    April 13, 2012

    @Phill, thank you for your reply... nice tip!

    I will be glad to help as soon as i understand a bit more about Cold Fusion...

    Regards.

    Inspiring
    April 13, 2012

    Let's think through what you're asking.  How can you identify which variable's name you wish to resolve without referring it at some point?  You need to know the name of a variable to do anything with it.

    What you're asking doesn't make sense.

    Take a step back... what is it you're trying to solve by thinking this is the way to solve it (if that makes sense)?

    --

    Adam

    April 13, 2012

    I needed to dynamicaly create a property in a structure with the same name of a variable but inside the scope of a function it just does not make any sense because i would allways get the name of the function paramenter instead of the actual variable name...outside that scope i declare de variable so i know the variable name.

    Something like this:

    myvar = "contents";

    obj = structnew();

    name = function_to_get_var_name(myvar);

    "obj.#name#" = arraynew(1);

    After analysing a the problem a bit more i found other solution in the context of my problem.

    Thanks for the replys.

    Inspiring
    April 13, 2012

    name = function_to_get_var_name(myvar);

    This demonstrates what I meant... to call function_to_get_var_name(), you need to code the very thing you want to return., eg: your code needs to specify myvar, and all the function is going to return is "myvar".  IE: you already need to know the answer to your question before you ask it.

    After analysing a the problem a bit more i found other solution in the context of my problem.

    Well that's good :-)

    --

    Adam

    BKBK
    Community Expert
    Community Expert
    April 13, 2012

    I want to declare a variable:

    myvar = "contents";

    and dinamically create an ouput like this: "the value of myvar is "contents""

    Arguably, the standard way in any language to dynamically manipulate a given parameter is by means of a function. The following example should give you a flavour.

    <cfscript>

    myvar = "contents";

    /* Call the function */

    doSomething(myvar);

    function doSomething (someParam) {

    writeOutput("The value of myvar is " & "'" & someParam & "'");

    }

    </cfscript>

    April 13, 2012

    I can do that, but that is static... you hardcoded "the value of myvar is"...

    I needed something like writeoutput("The value of" & function_to_get_var_name(myvar) & " is " & #myvar#);

    BKBK
    Community Expert
    Community Expert
    April 13, 2012

    Rockit8 wrote:

    I can do that, but that is static... you hardcoded "the value of myvar is"...

    I needed something like writeoutput("The value of" & function_to_get_var_name(myvar) & " is " & #myvar#);

    I would disagree. The 'myvar' in 'The value of myvar is...' is just text. I might as well have written "The value of my variable is...". In any case, by your own definition, you, too have indeed hardcoded! Your example does more or less what I did. But I understand what you mean.

    The main thing is the principle, which is, to use a function. We can easily modify the above code to make it more dynamic. It's just a matter of separating static from dynamic parts. For example, the display is done by the caller of the function, not by the function itself.

    <cfscript>

    myvar = "contents";

    /* Call the functions */

    writeoutput("The value of " & "'" & function_to_get_var_name(myvar)  & "'" & " after it undergoes transformation is " & doSomething(myvar));

    function function_to_get_var_name (someParam) {

    return someParam;

    }

    function doSomething (someOtherParam) {

    return "***" & someOtherParam & "***";

    }

    </cfscript>

    Owainnorth
    Inspiring
    April 13, 2012

    I really think you should buy a book or read the docs and examples online, these forums aren't just free tutorials.

    April 13, 2012

    I searched on google and didnt find anything usefull.

    I know that this might be simple stuff but i wasnt able to find anything about it.

    I can only get the name of properties in a structure, if you know some usefull article about this i'd apreciate it.