User-defined Functions

Contact Us or call 1-877-932-8228
User-defined Functions

User-defined Functions

User-defined functions are used to make common tasks easier and to make code more modular and easier to read.

Defining and Calling Functions

Functions are defined with the <cffunction> tag as follows. Like built-in functions, user-defined functions can receive arguments. Arguments are defined using the <cfargument> tag. If no default is defined with the default attribute, then the argument is required.

<cffunction name="function_name" returntype="type"> <cfargument name="arg" type="type" default="default"> </cffunction>

Here is an example user-defined function for adding numbers.

Code Sample:

<title>User-defined Function</title>

<cfset total = addNums(1)>

<cffunction name="addNums" returntype="numeric">
	<cfargument name="num1" type="numeric">
	<cfargument name="num2" type="numeric" default="0">
	<cfargument name="num3" type="numeric" default="0">
	<cfset sum=num1 + num2 + num3>
	<cfreturn sum>

Notice that user functions are called in the same way as built-in functions.