Dave over at edit.com came to me with a problem he was having referencing an array. He had an array stored in an instance variable of a ColdFusion component:
Launch code in new window » Download code as text file »
In one of the components functions, he was attempting to create a short-hand notation for this array so that his code would be more readable:
Launch code in new window » Download code as text file »
He then made changes to this arrProperties throughout the function. Later, when he dumped out the Instance variables, he saw that none of the changes he had made had held. The problem he was having here was due to the fact that in ColdFusion, arrays are passed by value, not by reference. That means that the line of code above actually duplicated the array and stored the duplicate in the variable arrProperties. Then, all changes in the function were made to the duplicate array and NOT to the original array of properties as he had intended.
This can be a bit confusing, especially if you look at the array append method:
Launch code in new window » Download code as text file »
The ColdFusion ArrayAppend() method does NOT return a value. That means that it directly updates the array that was passed to it. The only way that this could happen would be if the array passed to ArrayAppend() was passed by reference. So, who knows what is going on underneath the hood of some of these built in ColdFusion functions. But be aware that when you pass arrays around to custom UDFs, or even set them to new variables, they are passed by value.
And a final caveat, just because an array can be duplicated does not mean that all of its values can. If you have an array that has objects that are passed by reference such as Structures or Components, the duplicate array will have pointers to the SAME objects, NOT duplicates of them. So, be aware that you might be updating the same value from two different places.
Download Code Snippet ZIP File
Comments (0) | Post Comment | Ask Ben | Permalink | Other Searches | Print Page
There are no comments posted for this web log entry.