Functions

Functions typically manipulate data and return a result. CFML includes over 250 built-in functions. You can also use CFScript to create user-defined functions (UDFs), sometimes referred to as custom functions.

Functions have the following general form:

functionName([argument1[, argument2]]...)

Some functions, such as the Now function take no arguments. Other functions require one or more comma-separated arguments and can have additional optional arguments. All ColdFusion functions return a value. For example, Round(3.14159) returns the value 3.

Built-in functions

ColdFusion built-in functions perform a variety of tasks, including, but not limited to, the following:

For alphabetical and categorized lists of ColdFusion functions, see CFML Reference.

You use built-in functions throughout ColdFusion pages. Built-in functions are frequently used in a cfset or cfoutput tag to prepare data for display or further use. For example, the following line displays today's date in the format October 12, 2001:

<cfoutput>#DateFormat(Now(), "mmmm d, yyyy")#</cfoutput>

Note that this code uses two nested functions. The Now function returns a ColdFusion date-time value representing the current date and time. The DateFormat function takes the value returned by the Now function and converts it to the desired string representation.

Functions are also valuable in CFScript scripts. ColdFusion does not support ColdFusion tags in CFScript, so you must use functions to access ColdFusion functionality in scripts.

User-defined functions

You can write your own functions, user-defined functions (UDFs). You can use these functions in ColdFusion expressions or in CFScript. You can call a user-defined function anywhere you can use a built-in CFML function. You create UDFs using the cffunction tag or the CFScript function statement. UDFs that you create using the cffunction tag can include ColdFusion tags and functions. UDFs that you create in CFScript can only include functions.

User-defined functions let you encapsulate logic and operations that you use frequently in a single unit. This way, you can write the code once and use it multiple times. UDFs ensure consistency of coding and enable you to structure your CFML more efficiently.

Typical user-defined functions include mathematical routines, such as a function to calculate the logarithm of a number; string manipulation routines, such as a function to convert a numeric monetary value to a string such as "two dollars and three cents"; and can even include encryption and decryption routines.

Note:   The Common Function Library Project at http://www.cflib.org includes a number of free libraries of user-defined functions.

For more information on user-defined functions, see Chapter 9, "Writing and Calling User-Defined Functions".

Comments