Posted in ColdFusion | Posted on 10-17-2006 | 2,215 views
Over the past few days I've had multiple people ask me the same question - and that means one thing to me... blog post!
The question these people were asking was the same - I know how to write a UDF, but not sure how to actually use it on a page? By that they didn't mean the "function" syntax (x = foo()), but how to include the UDF so that it could be used on a page.
The answer is simple once you realize that a UDF is nothing more than another kind of ColdFusion variable. Consider this code:
2#x#
3</cfoutput>
What do you have to do to make this not throw an error? There are multiple ways to handle this. First, define it on the page:
2<cfoutput>#x#</cfoutput>
Another way:
2<cfoutput>#x#</cfoutput>
There are other ways of course, but you get the idea. So to use a UDF you follow the same rules. Here are two more examples using the same format as above:
2function cic() { return "monkey"; }
3</cfscript>
4<cfoutput>#cic()#</cfoutput>
And then the cfinclude version:
2<cfoutput>#cic()#</cfoutput>
Just like other variables, UDFs can be placed in the shared scopes. You can't do it directly though but rather must reassign:
2function dharma() { return "swan"; }
3request.dharma = dharma;
4</cfscript>
5
6<cfoutput>#request.dharma()#</cfoutput>


Take for example the UDF Test:
<cffunction name="Test">
<cfreturn ListToArray( "ben,ray" ) />
</cffunction>
This function just returns a simple array with two items in it. However, even though it returns an array, you cannot call the method and reference the value in ONE line of code:
#Test()[1]#
... will throw the error:
"Invalid CFML construct found"
You have to create an interim variable to do this:
<cfset arrNames = Test() />
#arrNames[ 1 ]#
This works fine. So, you might never come across this, but if you are getting this error, the error is NOT with the UDF itself, but rather with ColdFusion's compile time parsing issues. Personally, I think this is a *bug*... but that's just me.
Should/could not this be mentioned as well? :)
"How do I actually use a CFC to store my UDFs" :)
If I may step in for that one:
http://www.bennadel.com/index.cfm?dax=blog:257.vie...
[Add Comment] [Subscribe to Comments]