<head> web conference: October 24-26, 2008

Using Variables in ColdFusion MX Functions

CFFunction allows for an easier way of creating user defined functions (UDFs) in ColdFusion MX.

These UDFs enable the developer to encapsulate logic that would manipulate data with the possibility of returning a result.

The tag can be used with a minimum of one attribute, name, to surround the necessary code that the function will need to use while performing it's task.

Any arguments used within the CFFunction tag can be defined with the CFArgument tag.

Arguments are listed in the order that they will be called by the function, they have a minimum of one attribute, name, but can have default values with the possibility of having a specified data type.

Values defined by the CFArgument tag are run within their own protected scope, having no effect on similarly named local variables that may exist within the calling page.

The CFReturn tag is used to return a result value to the location where the UDF is called, this is not necessarily required for every UDF as some may simply perform a task such as adding a new user to a database.

UDFs are called in the same way as a built in ColdFusion function.

The example below illustrates a simple UDF that will receive a value and return it adding 10% and applying currency formatting. It also shows the UDF being called and printed to the screen.

Function code example one

Care must be taken with the creation of other variables within the UDF using the CFSet tag as the local variable scope of the calling page is exposed to a UDF.

Creating a variable within a UDF that has the same name as a calling page local variable this way will overwrite the values within the calling page unless the var keyword is used.

The var keyword creates a variable local to the UDF.

In the example above there is a variable being created called "percent" with a value of 10. If we were to create a local variable on the calling page with the same name prior to the function call it would now have a value of 10 regardless of it's original.

Here is that same UDF with the variable now initialised as local to the UDF.

Function code example two

The same care must also be taken with queries used within UDFs, by default they are created within the local scope of a page. If your UDF has a query with an identical name as that of one on the calling page the result set will be overridden by the query in the function.

The following example shows the query name being created as a local variable within the UDF with an empty string as it's value.

Function code example three

Remember that any value created by the CFArgument tag is local to the UDF and therefore runs in it's own protected scope.