Leeish
Leeish

Reputation: 5213

Variable values changing between requests in ColdFusion

Consider the following code:

<cfset local.quiz = getQuiz(param1,param2) />
<!--- returns a struct that has a key called unlock_at --->
<cfset quiz.unlock_at = (quiz.unlock_at EQ '') ? '' : DateConvert('utc2Local',createODBCDateTime(ISOToDateTime(quiz.unlock_at))) />

This is how I origionally wrote my code. When I called the page that ran this code multiple times, the value of quiz.unlock_at was changing in 6 hour increments (the amount of adjustment in the function). When I say increments I mean first page load the time was say 12:00. The next page load 6:00, the next page load 00:00 and so on. The physical time was changing each time. I changed the code to this:

<cfset local.unlock_at = (quiz.unlock_at EQ '') ? '' : DateConvert('utc2Local',createODBCDateTime(ISOToDateTime('#quiz.unlock_at#'))) />

The first thing is I'm storing the value in a local variable and no longer updating the existing struct. The second thing is I am passing in the date to the function as a string and not as the variable. I wasn't sure how it was getting altered. In either case:

How the heck was this changing between requests. I didn't think these variables lives between page requests. All of this code is inside a function that lives inside a CFC. What of any of that data is persistent. I called the page a few times and watched the dates change then opened a NEW browser and the data was altered too. How is that possible?

Is this a scoping issue, a data persistence issue with components? Threw me for a loop and I still and not sure what happened and until I do I'm afraid I may have other issues.

Upvotes: 0

Views: 385

Answers (1)

Leeish
Leeish

Reputation: 5213

I figured it out. Grrr...

The function getQuiz created a struct and then cached it. The reason being is that it's an API call and I don't want to have to run an API call every time for data that doesn't change that often. So what I was doing was:

<cffunction name="getQuiz">
<cfset local.variable = {} />
<!--- Load Sturct Data --->
<!--- CachePut the variable --->
<cfreturn variable />
</cffunction>
<cfset quiz = getQuiz() />
<cfset quiz.unlock_at = 1 />
<!--- At this point I have actually edited a direct reference to the cached variable quiz even though I tried locally scoping it etc.

So, apparently returning a struct is the same as passing a struct into a function, i.e. it passes the struct by reference not by value. For some reason I thought returning a struct didn't return it as a reference, but it makes sense because that is the way CF passes values between functions.

Upvotes: 1

Related Questions