+44 (0) 845 260 0726

Pixl8

You are:

  • Home
  • Blogs
  • The difference between variables.instance and instance
  • | Share

The difference between variables.instance and instance

Alex Skinner   Posted: 29 January 2007

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 --------

<cfcomponent name="test" hint="my test lazy 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 --------

<cfset testCFC=createobject("component","test").init(datasource="foo")>
<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.

<cffunction name="init" returntype="test">
<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>
  1. Bookmark & Share :
  2. Delicious
  3. Digg
  4. Facebook
  1. Comments (0)
  2. 627 Views