The difference between variables.instance and instance
Trouble shooting some bung code I came across a weird one today. This highlights the need to scope variables.
Quite often for cfc's when storing private instance data developers use a structure called instance under the variables scope or private. You can of course just use variables, but anyway it seems a trend in some code i've been reviewing.
Anyway I suppose it's better than using the this scope as it means the data is private to the cfc instance.
There is however a difference between variables.instance and instance, the test case I created below shows how lazyness can byte you in the arse.
this.cfc --------
<cffunction name="init" returntype="test">
<cfargument name="datasource" type="string" required="yes">
<!--- using instance as a scope for private instance data --->
<cfset instance.datasource=arguments.datasource>
<cfreturn this>
</cffunction>
</cfcomponent>
test.cfm --------
<h1>Having a form field named instance breaks my cfc</h1>
<form name="thoughshallscope" action="" method="post">
<input type="hidden" name="instance" value="oh dear">
<input type="submit" name="gostuff" value="break my cfc">
</form>
<br>
<a href="?instance=KillthatCFCYeah!!">Having a link with the word instance in isn't good either</a>
This can be fixed by modifying the init method firstly to use variables.instance but secondly to make sure you use structNew() before working on a structure.
<cfargument name="datasource" type="string" required="yes">
<!--- using instance as a scope for private instance data --->
<cfset variables.instance=structNew()>
<cfset variables.instance.datasource=arguments.datasource>
<cfreturn this>
</cffunction>
