Search This Blog

Tuesday, October 16, 2007

Adding elements to a structure

While I was playing with a request structure in coldfusion I come across a strange scenario with adding elements in the structure
There are 3 ways to add an element in the structure

<cfset request.sMyStructre[elementid] = value />

<cfset structInsert(request.sMyStructre,elementid,value) />

<cfset request.sMyStructre.elementid = value />

Even though the result of those 3 commant 99% of the times is the same I found a case where they produce a different output

I create an object test.cfc

<cfcomponent output="true">

<cfset
request.sReqObjects1 = structNew() />

</cfcomponent>


and a test cfm page
<cfset request.sReqObjects1 = structNew() /> <Cfset request.sReqObjects1['t2'] = createObject("component","Test") /> using the request.sReqObjects1['t2']<br />
<cfdump var="#request.sReqObjects1#">
<cfset structInsert(request.sReqObjects1,'t3',createObject("component","Test")) /> using the structInsert(request.sReqObjects1,'t3',createObject("component","Test")) <br /> <cfdump var="#request.sReqObjects1#"> <Cfset request.sReqObjects1.t1 = createObject("component","Test") />
using the request.sReqObjects1.t1
<cfdump var="#request.sReqObjects1#">


And the output was
using the request.sReqObjects1['t2']
struct [empty]
using the structInsert(request.sReqObjects1,'t3',createObject("component","Test"))
struct [empty]
using the request.sReqObjects1.t1
struct
T1
component Test


The only reason I can thing for this is that
using [request.sReqObjects1['t2'] =] or [structInsert ] creates the element on a different memory location and just adds a reference to that location in the structure, which then is cleared by the <cfset request.sReqObjects1 = structNew() /> in the cfc constructor. But when using the <Cfset request.sReqObjects1.t1 = the new element is actually created in the memory space of the structure.

No comments: