Skip to main content
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Tom Chiverton
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Tom Chiverton ( @thefalken )

ColdFusion's Auto-Struct-Generation Caveat

By
Published in

One thing that ColdFusion will do for you is auto-generate struct objects when they are referenced as part of a variable name. For instance, if you have no previously defined variables and you run this line of code:

<!--- Set key value. --->
<cfset objCouple.Boy.Name = "Ben" />

... ColdFusion will automatically create the structure "objCouple". Then, within that structure, it will automatically create the key, "Boy", and set it equal to a new struct. Then it will automatically create the key, "Name", within that structure and assign the value "Ben" to that key.

I personally never do this as I like to explicitly define my structures, but, it's kind of neat. The caveat though, is that this only works with "valid variable names". I am not sure what the exact definition of that is, but basically you can only have names that begin with letters and under scores (I think), but the big caveat is that you cannot use array notation when defining this struct. For example:

<!--- Set key value. --->
<cfset objCouple[ "Girl" ].Name = "Molly" />

... throws a coldfusion.runtime.UndefinedElementException:

Element Girl is undefined in a CFML structure referenced as part of an expression.

So, I personally wouldn't recommend letting ColdFusion auto-generate anything for you (using this methodology or through the use of StructGet() for that matter), but if you are going to, just be careful about how you want to name things.

Want to use code from this post? Check out the license.

Reader Comments

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel