

|
|
Variables in CFML; Assignment by Value and ReferenceAssignment by ValueIn almost all cases assignments in CFML are by value. In other words an assignment creates a copy of the value. The following code illustrates this: <cfset foo = 3> The end result of the following code is that foo holds the value "4" and fee holds the value "3". The second line made a copy of the then current value of foo, subsequent changes to foo are not reflected in fee. The two variables are completely independent of one another. ColdFusion performs assignment by value for all variable types except structures and queries. When using the assignment operator ("=") these are passed by reference as described below. Assignment by ReferenceAssignment by reference is a very powerful, but often confusing aspect of CFML development with structures and queries. Unlike other data types structures and queries are not copied by value when using the equals ("=") sign, instead a reference or pointer to them is created. This reference can be thought of as a link to the original data. The following code illustrates this: <cfset foo = StructNew()>
<cfset foo = StructNew()> To properly use this feature you must first have an understanding of differences between StructCopy() and Duplicate(). StructCopy() will perform a copy of only the "top" structure. Any sub-structures contained within will be passed by reference. Duplicate(), on the other hand, does indeed copy the entire structure and all its children, no pointers are created. In common use unless you have a very good understanding of the ramifications of this we recommend that you always use Duplicate(). Assignment by reference may not appear useful at first glance but is actually immensely useful in certain contexts:
One important issue to understand is that references directly access the target structure. So if the target structure requires locking (because it's in the application, session, or server scopes) then the reference variable also requires locking. This topic is fully detailed in our Guide to Locking. Locking references can become complicated very quickly so it's generally recommended that only advanced developers create references to shared scopes. |