User Guide

250 Chapter 13 Extending ColdFusion Pages with CFML Scripting
Defining and Using Custom Functions
You can define custom functions (also known as user-defined functions) and use
them in your application pages as you do standard ColdFusion functions. This
allows you to create a function for an algorithm or procedure that you use frequently,
and then use the function wherever you need the procedure. If you must change the
procedure, you change only one piece of code. You can use your function anywhere
that you can use a ColdFusion expression: in tag attributes, between # signs in
output, and in CFScript code.
Defining functions
You define functions using CFScript, in a manner similar to defining JavaScript
functions. The function must return a value. Functions can be recursive, that is, the
body of a function can call the function.
You can define a function in the following places:
On the page where it is called (even after it is called, although this is not
recommended).
On a page that you include using a
cfinclude tag. The cfinclude tag must be
executed before the function gets called. For example, you can define all your
applications functions on a single page and place a cfinclude tag at the top of
pages that use the functions.
Syntax Use the following syntax inside a
cfscript tag to define a function:
function functionName( [paramName1[, paramName2...]] )
{
CFScript Statements
}
functionName
The name of the function. You cannot use the name of an standard ColdFusion
function name. You cannot use the same name for two different function
definitions. Function names cannot include periods.
paramName1...
Names of the parameters required by the function. The number of arguments
passed into the function must equal or exceed the number of parameters in the
function definition. If the calling page omits any of the required parameters,
ColdFusion generates a mismatched argument count error.
The body of the function definition must consist of one or more valid CFScript
statements.