User-defined function names are essentially ColdFusion variables. ColdFusion variables are names for data. Function names are names (references) for segments of CFML code. Therefore, like variables, functions belong to scopes.
Like ColdFusion variables, UDFs exist in a scope:
You can now use the function from any page in the Request scope by calling Request.MyFunc.
The following table describes the advantages and disadvantages of scopes that you might considering using for your functions:
Scope |
Considerations |
---|---|
Application |
Makes the function available across all invocations of the application. Access to UDFs in Application scope is multithreaded and you can execute multiple copies of the UDF at one time. |
Request |
Makes the function available for the life of the current HTTP request, including in all custom tags and nested custom tags. This scope is useful if a function is used in a page and in the custom tags it calls, or in nested custom tags. |
Server |
Makes the function available to all pages on a single server. In most cases, this scope is not a good choice because in clustered systems, it only makes the function available on a single server, and all code that uses the function must be inside a cflock block. |
Session |
Makes the function available to all pages during the current user session. This scope has no significant advantages over the Application scope. |
You can effectively manage functions that are used in application pages and custom tags by doing the following:
This way you only need to include the functions once per request and they are available throughout the life of the request. For example, create a myFuncs.cfm page that defines your functions and assigns them to the Request scope using syntax such as the following:
function MyFunc1(Argument1, Argument2)
{ Function definition goes here }
Request.MyFunc1 = MyFunc1
The application page includes the myFuncs.cfm page:
<cfinclude template="myfuncs.cfm">
The application page and all custom tags (and nested custom tags) call the functions as follows:
Request.MyFunc1(Value1, Value2)
Using the Request scope for static variables and constants
This section describes how to partially break the rule described in the section Referencing caller variables. Here, the function defines variables in the Request scope. However, it is a specific solution to a specific issue, where the following circumstances exist:
In these circumstances, you can improve efficiency and save processing time by defining your function's variables in the Request scope, rather than the Function scope. The function tests for the Request scope variables and initializes them if they do not exist. In subsequent calls, the variables exist and the function does not reset them.
The NumberAsString function, written by Ben Forta and available from www.cflib.org, takes advantage of this technique.