Variables in CFML; Creating Variables

Before a variable can be used it must be created. ColdFusion doesn't require the programmer to explicitly create, or declare variables before data can be assigned to them. In fact in ColdFusion the same action that creates a variable must also assign an initial value. Also CFML is what's called a loosely typed language meaning that you don't have to specify what type of data a variable will hold. Any variable can hold any type of data and this can be changed at any time.

We'll cover the specifics of creating variables here and detail the various aspects of assigning data to them in the next section.

Naming Variables

All variables in CFML must have a name with which the variable is identified and referenced. This name will be used throughout your code to identify the values contained in the variable.

Rules for Variable Naming

Here are some rules for naming variables in CFML:

  • All variable names in CFML must begin with a letter or, in MX only, with a letter or an underscore ("_") character. Names may then contain letters, numbers and the underscore character ("_").
  • Periods, quotes, pound signs ("#") and square brackets ("[" and "]") are used as qualifiers when working with compound variable names and array notation. Although they may be part of a variable reference they are not part of the variable name.
  • CFML variables are not case sensitive. This means that you can create a variable called "foo" and access it with "Foo" or "FOO" or "fOo". Despite this we recommend that you honor case as a best practice. Many languages are case sensitive (Java, JavaScript, C++, etc) and this is simply a good habit to get into.
  • Although it is possible in some cases it is highly reccommended that you do not use reserved words in CFML as variable names. Names of functions, tags, scopes, etc. should not be used. In addition to avoid confusion you should avoid using names that are reserved words in supporting languages such as SQL, JavaScript, CSS or DHTML.

Suggestions for Variable Naming

Many developers adopt a form of Camel Case to name variables. This simply means that the first significant letter of each word in a compound name is capitalized. In full Camel Case every significant letter is capitalized while in headless Camel Case only the second and subsequent significant letters are capitalized. For example the variable name "myvariablename" would be "MyVariableName" in full Camel Case and "myVariableName" in headless Camel Case. Other examples are "MyCounter", "CustomerName" and "currentItem".

Your variable names should strike a balance between concise (but cryptic) and long (but cumbersome). For example a variable might be used to contain the first name of a customer. The name "CN", while valid, may be too short and could easily be confused with something else. However calling it "CurrentCustomersFirstName", while descriptive, is long enough to become cumbersome and distracting. Something like "CustFName" or "CFName" should be descriptive enough without bogging down your code. There is no perceptible performance gains to be found by using short names over long names.

Standardizing variable names can improve the maintainability of your code greatly. For example you might use a prefix for variables containing certain data. It can be assumed that there will be many pieces of data associated with a customer. You could decide to prefix all such variables with "Cust_" as in "Cust_Name", "Cust_Phone", "Cust_Address", etc. You could then reuse that convention for other variable groups. This customer might have a sales representative associated with them and you might use the prefix "Rep_" to distinguish that data. You might then have "Rep_Name", "Rep_Phone", "Rep_Address", etc.

(In real-world applications the above is a perfect example when to use a complex type likes structures or arrays. All of the data about a customer could be stored in a single variable, a structure for example, called "Customer".)

Prefixing is also valuable when working with complex variable objects (explained later). For example you might prefix all of your query (recordset) variable names with "q" or "Qry_" and your structure names with "s" or "Struct_". In the same way you might prefix a group of related variables. All of the variables related to search functionality might begin with "Search_" or "Srch_". A formalized version of this dubbed Hunagrian Notation was created at Microsoft by Charles Simonyi. MSDN has his excellent orginal essay on the topic available.

You may also consider standardizing "workhorse" variable names such as loop counters. Many people use the simple variable name "i" as a counter while others use "Cnt" or "Count". Doing this results in code that's easier to read and understand.

The <CFSET> Tag

The most common way to create a variable in ColdFusion is with the CFSET tag. This is one of the simplest tags available in CFML and takes the format: <cfset variableName = Value>. Where "variableName" is a valid variable name (as described above) and "Value" is the data being assigned to that name. "Value" can be an expression or function which results in a value and may be either a simple or complex data type.

CFML is somewhat unique in that the variable name used in the CFSET tag can itself be a dynamic value (variable). This will be fully covered in the section on dynamic variables. Some examples of CFSET tags follow:

  • <cfset myVar = "Hello">
  • <cfset Count = 7>
  • <cfset Result = 3 + 6>
  • <cfset "#myVar#" = "Goodbye">
  • <cfset myVar & Cnt = "Goodbye">

The CFSET tag will be used extensively throughout this guide.

The <CFPARAM> Tag

Often a CFML template will require a variable to be passed into it to complete processing. Variables, when being passed into a program or web page, are often called parameters or arguments. The CFPARAM tag is a "shortcut" tag that allows the programmer to test for the existence of parameters, create and assign data to them if needed, and test their type.

The tag accepts a variable name using the Name attribute and will test to see if that variable exists. If the variable doesn't exist the tag can set a default value for the variable using its Default attribute. Lastly using the Type attribute the tag can also check that the variable is of a specific variable type.

There are four valid combinations of attributes:

AttributesBehavior
Name Check if a variable exists. If the variable specified does not exist an error will be thrown.
Name, Type Check that a variable exists and that it is a certain type. If the variable either does not exist or does exist but is not of the specified type an error will be thrown.
Name, Default Ensure that a variable exists. If the specified variable exists no action is taken, if it does not the variable is created and the populated automatically with the value of the Default attribute.
Name, Default, Type Will first check to see if the variable exists. If it doesn't the variable is created with the default value. The tag then checks the variable type. If the type is incorrect an error will be thrown. When using the CFPARAM like this you should insure that the default value and the type paramter are compatible.

The type attribute can be used to test for any of the standard variable types (Array, Binary, Boolean, Date, Numeric, Query, String, Struct, and UUID). In addition the Type attribute can also accept the value of "Any" (which allows any value) and "VariableName" which only allows valid ColdFusion variable names (and is very useful when creating custom components which can accept return variable names).

One potential stumbling block is that although the value contained within a UUID has been standardized the display of UUIDs has not been. <CFPARAM>, unfortunately, is only able to validate UUIDs in the specific format provided by CreateUUID(). Valid UUIDs from other sources (for example SQL server) which feature different formatting are not able to be used.

Errors thrown by the CFPARAM tag can be intercepted and processed with the CFTRY/CFCATCH tags.

The SetVariable() Function

The SetVariable() function accepts two parameters: Name and Value. Both of these parameters can accept dynamic values.

The SetVariable function is useful in highly dynamic situations when the variable name must be programmatically constructed. If the dynamic variable is simple (a concatenation of strings) then using the CFSET tag is recommended. These topics will be covered in more detail in the section on dynamic variables.

Creating Variables in CFSCRIPT

Within CFSCRIPT variable creation uses a simple "name = value;" format (with name being any valid variable name, structure or array reference). The semi-colon simply denotes the end of a statement in CFSCRIPT and is not unique to variable creation. Some examples:

  • myVar = "Hello";
  • Count = 7;
  • Result = 3 + 6;

Variables in CFSCRIPT follow all of the same naming and access rules as variables in general CFML.

Creating Cookies

Cookies variables are created with the CFCOOKIE tag and will be explained more fully in the section on the Cookie variable scope.

Automatic Generation

Many variables in CFML are generated automatically. There are four main categories of these variables:

Server Generated: When the server starts several variables are created which describe the environment. Server.ColdFusion.ProductName and Server.OS.Name are examples of these variables.

Tag Generated: Many ColdFusion tags will return data as variables. Examples are CFFILE, CFHTTP, CFPOP, CFDIRECTORY, and CFQUERY.

Event Generated: During processing several ColdFusion events can generate variables. Calling a CFML Custom Tag results in several special ThisTag variables, a ColdFusion error (when caught by the CFERROR tag) results in a host of variables, any ColdFusion request automatically populates the CGI variable set, submitting a form automatically generates the appropriate FORM variables and so on.

Application Configuration Specific: The configuration (if any) of a ColdFusion application may create several variables. Using the CFAPPLICATION tag will generate the Application.ApplicationName variable. Enabling Session or Client variables will result in the creation of many standard variables.

Quick reference guides containing overviews of this information and all the variables created are available online in PDF format from the ColdFusion Documentation Support Center for the following versions:

These reference cards are invaluable resources. Developer's should use them to ensure that the variables that they create do not conflict with automatically generated variables.

29 Current Sessions; Time: 15:13:06 06-01-2009; Tick: 891