storing udf's in a different scope
On one of the lists today someone asked about how to store a udf on a cfm page in a different scope, such as the application scope.
Something that not many developers realise is that when you create a function in a cfm page (actually for a cfc as well) it is stored in the variables scope for that page. So, if in test.cfm you create the following function:
<cffunction name="foo" access="public" returntype="boolean" output="false">
<cfreturn True />
</cffunction>
Then you can of course call the function using the following syntax:
<cfset variables.result = foo() />
but you can also access the function by using:
<cfset variables.result = variables.foo() />
because the foo() function is stored in the variables scope. now what if you wanted to access it using application.foo() ? Well you can not do this:
<cfset application.foo = foo />
That code will bomb and tell you that foo isnt defined. I am not exactly sure why this is, but you can do this:
<cfset application.foo = variables.foo />
and then you can call the function from then on using application.foo().
To see this in action, create a udf on a .cfm page and then dump the variables scope like so:
<cfdump var="#variables#" />
And to see it in action in a cfc, put the following method in one of your cfc's that has some other methods in it:
<cffunction name="dumpVariables" access="public" returntype="struct" output="false">
<cfreturn variables />
</cffunction>
and then call the method from a .cfm page and dump the results. you will see all of the methods in the cfc. This is also why if I am ever storing variables inside of a component, I use variables.properties structure instead of using the variables scope directly.
Posted on Tue. September 13, 2005 by Ryan Guill