setting a dynamic variable name

This is probably known to many, but you can set a variable with a dynamic name. I've only come across one or two instances in ten years where this is necessary. Those times have always been to quickly fix existing code and remove hard-coding of variable names.

There's always 10 ways to get to the same destination with programming, and I usually don't take this one. However, it is an option, so I'm demonstrating it here.

An example is perhaps when you need to set a variable for each student (Mark_classes, Tom_classes), and then assign a value to that new variable. This can be done with the code below:

<cfoutput query="myQuery">
   <cfset "#myQuery.Name#_classes" = myQuery.numberOfClasses>

Just be sure to put the quotes around the dynamic variable name.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Dan G. Switzer, II's Gravatar Well that method has worked for a while, I prefer:

[cfset variables[myQuery.Name & "_classes"] = myQuery.numberOfClasses /]

Well it's more verbose, I think it's more clear. It's also an officially supported method of dynamically naming variables. The other benefit is this method works for both setting and getting variables.
# Posted By Dan G. Switzer, II | 1/28/08 9:35 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.