ColdFusion Programming/variables

Variables are used extensively in Coldfusion.

CFSET edit

The basic way to set a variable is to use cfset. There is no difference between setting a variable as a string or a number. Strings must be inclosed by an opening and closing ' or ".

<cfset tempnum = 5>
<cfset tempstr = "Hello">

CFOUTPUT and Pound Signs edit

The basic way to convert the variable name into its value is to place pound signs around the variable name. The variable name and pound signs must be placed inside of a cfoutput tag.

<cfset tempvar = 8>
<cfoutput>#tempvar#</cfoutput>

Additionally you can perform calculations within the pound signs.

<cfoutput>#1+1#</cfoutput>

Output: 2

Evaluate() edit

An advanced feature is to use the evaluate() function. ColdFusion's evaluate function lets you evaluate a string expression at runtime.

<cfset x = "int(1+1)">
<cfset y = Evaluate(x)>

It is particularly useful when you need to programatically choose the variable you want to read from.

<cfset x = Evaluate("queryname.#columnname#[rownumber]")>

Since ColdFusion MX 6.1 it has been highly recommended that developers stay away from using Evaluate() for most common tasks. Instead it is recommended that developers use bracket notation.

<cfset queryname[columnname][rownumber] />

Since the entire variables system is based on a structure system, this design can be used on any type of variable.

<cfset x = "foo" />
<cfoutput>#variables['x']#</cfoutput>

Variable Lookup edit

  • Local variables
  • CGI variables
  • File variables
  • URL variables
  • Form variables
  • Cookie variables
  • Client variables

Session Variables edit

Session variables are easy to use and create. A session variable is used to allow variables to live beyond the life of the page in which they are created in but will die when the users session dies.

On every page of your application where you are going to use the session variable you need to include:

<cfapplication sessionmanagement="true">

This code should normally be placed in your Application.cfm file.

Then to set a session variable on page 1:

<cfset session.name = "Bob">

And on a different page called after page 1:

<cfoutput>#session.name#</cfoutput>

Client Variables edit

<cfset tempvar = 8> <cfoutput>#tempvar#</cfoutput>

Application Variables edit

Server Variables edit