By Hal Lichtin
Sr. Technical Writer
Macromedia, Inc.
A ColdFusion variable is created by assigning a value to
it. Most commonly, you create variables by using the CFSet
tag. You can also use the CFParam
tag and assignment statements in CFScript. Tags that create
data objects also create variables. For example, the cfquery
tag creates a query object variable.
ColdFusion automatically creates some variables that provide
information about the results of certain tags or operations.
ColdFusion also automatically generates variables in certain
scopes, such as Client and Server. For information on these
special variables, see the CFML Quick Reference
and the documentation of the CFML tags that create these
variables.
ColdFusion does not support variables with Null - or no
- values. Therefore, ColdFusion generates an error when
it tries to use a variable before it is created. This can
happen, for example, when processing data from an incompletely
filled form. To prevent such errors, test for the variable's
existence before you use it. For more information on testing
for variable existence, see Developing ColdFusion Applications.
For more information on how to create variables, see Creating
and Using Scope Variables.
Variable Naming Rules
When naming ColdFusion variables and form fields, follow
these guidelines:
- A variable name must begin with a letter, which can
be followed by any number of letters, numbers, and underscore
characters.
- A variable name cannot contain spaces.
- A query is a type of variable, so it cannot have the
same name as another local variable in the current ColdFusion
application page.
- Use consistent capitalization, to keep your code consistent.
(ColdFusion variables are not case-sensitive.)
- When creating a form with fields that are used in a
query, match form field names with the corresponding database
field names.
- Prefix each variable's name with its scope. Although
some ColdFusion programmers do not use the Variables prefix
for local variable names, you should use prefixes for
all other scopes. Using scope prefixes makes variable
names clearer and increases code efficiency. In some cases,
you must prefix the scope. For more information, see Creating
and Using Scope Variables.
You can classify a variable using these characteristics:
- The data type of the variable value, which indicates
the kind of information a variable represents, such as
number, string, or date
- The scope of the variable, which indicates where the
information is available and how long the variable persists
ColdFusion is often referred to as "typeless" because you
do not assign types to variables and ColdFusion does not
associate a type with the variable name. However, the data
that a variable represents does have a type, and the data
type affects how ColdFusion evaluates an expression or function
argument. ColdFusion can automatically convert many data
types into others when it evaluates expressions. In fact,
for simple data, such as numbers and strings, the data type
is unimportant until the variable is used in an expression
or as a function argument.
Note: Although ColdFusion variables do not
have types, it is often convenient to refer to a variable's
type as a shorthand for the type of data that the variable
represents.
ColdFusion variable data belongs to one of these type categories:
- Simple: Represents one value. ColdFusion simple data
types include numbers, strings, Booleans, and date-time
variables. You can use simple data types directly in ColdFusion
expressions.
- Complex: A container for data. Complex variables generally
represent more than one value. ColdFusion built-in complex
data types include arrays, structures, and queries.
You cannot use a complex variable, such as an array, directly
in a ColdFusion expression, but you can use simple data
type elements of a complex variable in an expression.
For example, with a one-dimensional array of numbers called
myArray, you cannot use the expression myArray
* 5. However, you could use an expression myArray[3]
* 5 to multiply the third element in the array
by 5.
- Binary: "Raw" data, such as the contents of a GIF file
or an executable program file.
- COM, CORBA, and Java (including EJB) objects: Complex
objects that you create and access using the cfobject
tag. For more information on using these objects, see
Developing ColdFusion Applications.
Note: Unlike some programming languages,
ColdFusion does not have the concept of NULL values. (ColdFusion
does have empty strings.) To prevent errors, you must make
sure that variables exist before using them. For more information,
see the section "Ensuring that Variables Exist" in Developing
ColdFusion Applications.
Numbers
ColdFusion supports integers and real numbers. You can
intermix integers and real numbers in expressions; for example,
1.2 + 3 evaluates to 4.2.
Integers
ColdFusion supports integers between -2,147,483,648 and
2,147,483,647 (32-bit signed integers). You can assign a
value outside this range to a variable, but ColdFusion initially
stores the number as a string. If you use it in an arithmetic
expression, ColdFusion converts it into a floating point
value, preserving its value, but losing precision. The following
code shows this:
<cfset mybignum=12345678901234567890>
<cfset mybignumtimes10=(mybignum * 10)>
<cfoutput>mybignum is: #mybignum#</cfoutput><br>
<cfoutput>mybignumtimes10 is: #mybignumtimes10# </cfoutput><br>
This code generates the following output:
mybignum is: 12345678901234567890
mybignumtimes10 is: 1.23456789012E+020
Real numbers
Real numbers, numbers with a decimal part, are also known
as floating point numbers. ColdFusion real numbers can range
from approximately -10300 to approximately 10300.
A real number can have up to 12 significant digits. As with
integers, you can assign a variable a value with more digits,
but the data is stored as a string. It is converted to a
real number, and can lose precision when you use it in an
arithmetic expression.
You can represent real numbers in scientific notation.
This format is xEy,
where x
is a positive or negative real number in the range 1.0 (inclusive)
to 10 (exclusive), and y
is an integer number. The value of a number in scientific
notation is x times 10y. For example, 4.0E2 is
4.0 times 102, which is equal to 400. Similarly,
2.5E-2 is equal to 2.5 times 10-2, which is equal
to 0.025. Scientific notation is useful for writing very
large and very small numbers.
Strings
In ColdFusion, text values are stored in strings. Strings
are text delimited by either single or double quotes. For
example, the two strings below are equivalent:
"This is a string"
'This is a string'
An empty string can be written in these ways:
- As "" (a pair of double quotes with nothing in between)
- As " (a pair of single quotes with nothing in between)
Strings can be of any length, limited by the amount of
available memory on the ColdFusion Server. There is, however,
a 64K limit on the size of text data that can be read from
and written to a ColdFusion database or HTML text area.
The ColdFusion Administrator lets you increase the limit
for database string transfers, but doing so can reduce server
performance. To change the limit, select the Enable retrieval
of long text option on the CF Settings page for the data
source.
To include a single-quote character in a string that is
single-quoted, use two single quotes (this is known as escaping
the single quote). The following example uses escaped single
quotes:
<cfset myString='This is a single quote: '' This is a double quote: "'>
<cfoutput>#mystring#</cfoutput><br>
To include a double-quote character in a double-quoted
string, use two double quotes (this is known as escaping
the double quote). The following example uses escaped double
quotes:
<cfset myString="This is a single quote: ' This is a double quote: """>
<cfoutput>#mystring#</cfoutput><br>
Because strings can be in either double quotes or single
quotes, both of these examples output the same text:
This is a single quote: ' This is a double quote: "
To insert a pound sign in a string, you must escape the
pound sign, as in:
"This is a pound sign ##"
Lists
ColdFusion has functions that operate on lists, but it
does not have a list data type. In ColdFusion, a list is
just a string that consists of multiple entries separated
by delimiter characters. The default delimiter for lists
is the comma. If you use any other character to separate
list elements, you must specify the delimiter in the list
function.
You can specify alternative delimiter characters. For example,
you can tell ColdFusion to interpret a comma or a semicolon
as a delimiter, as the following example shows:
<cfset MyList="1,2;3,4;5">
<cfoutput>
List length using ; and , as delimiters: #listlen(Mylist, ";,")#<br>
List length using only , as a delimiter: #listlen(Mylist)#<br>
</cfoutput>
This example displays the following output:
List length using ; and , as delimiters: 5
List length using only , as a delimiter: 3
Each delimiter must be a single character. For example,
you cannot tell ColdFusion to require two hyphens in a row
as a delimiter.
If a list has two delimiters in a row, ColdFusion ignores
the empty element. For example, if MyList is "1,2,,3,,4,,,5"
and the delimiter is the comma, the list has 5 elements
and list functions treat it identically to "1,2,3,4,5".
Booleans
A Boolean value represents whether something is true or
false. ColdFusion has two special constants-TRUE and FALSE-
to represent these values. For example, the Boolean expression
1 IS 1 evaluates to TRUE. The expression "Monkey" CONTAINS
"Money" evaluates to FALSE.
Boolean constants can be used directly in expressions,
as in this example:
<cfset UserHasBeenHere = TRUE>
In Boolean expressions, the values TRUE, non-zero numbers,
and the string "Yes" are equivalent. The values FALSE, 0,
and the string "No" are equivalent.
Boolean evaluation is not case sensitive.
Date-Time Values
ColdFusion can perform operations on date and time values.
Date-time values identify a date and time in the range 100
AD to 9999 AD. Although you can specify just a date or a
time, ColdFusion uses one data type representation, called
a date-time object, for date, time, and date and time values.
ColdFusion provides many functions to create and manipulate
date-time values and to return all or part of the value
in several different formats.
You can enter date and time values directly in a cfset
tag with a constant:
<cfset myDate = "October 30, 2001">
When you do this, ColdFusion stores the information as
a string. If you use a date-time function, ColdFusion stores
the value as a date-time object, which is a separate simple
data type. When possible, use date-time functions such as
CreateDate and
CreateTime to
specify date and times, because these functions can prevent
you from specifying the date or time in an invalid format
and they create a date-time object immediately.
Date and time formats
You can directly enter a date, time, or date and time,
using standard US date formats. ColdFusion processes the
two-digit-year values 0 to 29 as 21st century
dates; it processes the two-digit-year values 30 to 99 as
20th century dates. Time values are accurate
to the second.
| To specify |
Use these formats |
| Date |
October 30, 2001
Oct 30, 2001
Oct. 30, 2001
10/30/1
2001-10-30
10-30-2001 |
| Time |
02:34:12
2:34a
2:34am
02:34am
2am |
| Date and Time |
Any combination of valid
date
and time formats, such as these:
October 30, 2001 02:34:12
Oct 30, 2001 2:34a
Oct. 30, 2001 2:34am
10/30/1 02:34am
2001-10-30 2am
10-30-2001 2am |
Locale-specific dates and times
ColdFusion provides several functions that let you input
and output dates and times (and numbers and currency values)
in formats that are specific to the current locale. A locale
identifies a language and locality, such as English (US)
or French (Swiss). Use these functions to input or output
dates and times in formats other than the US standard formats.
(Use the SetLocale
function to specify the locale.) The following code shows
an example:
<cfset oldlocale = SetLocale("French (Standard)")>
<cfoutput>#LSDateFormat(Now(), "ddd, mmmm dd, yyyy")#</CFOUTPUT>
This code outputs a line like this:
ven., juin 15, 2001
For more information on International functions, see CFML
Reference.
How ColdFusion stores dates and times
ColdFusion stores and manipulates dates and times as date-time
objects. Date-time objects store data on a timeline as real
numbers. This is done for efficiency in evaluation and because
it directly mimics the method used by many popular database
systems. In date-time objects, one day is equal to the difference
between two successive integers. The time portion of the
date-and-time value is stored in the fractional part of
the real number. The value 0 represents 12:00 AM 12/30/1899.
Although you can use arithmetic operations to manipulate
date-and-time values directly, this method can be troublesome.
Use the ColdFusion date-time manipulation functions instead.
Binary Data Type and Base64 Encoding
Binary data is "raw" data, such as the contents of a GIF
file or an executable program file. You do not normally
use binary data directly, but you can use the cffile
tag to read a binary file into a variable. This is typically
done for conversion to Base64 encoding before transmitting
the file by e-mail.
Base64 format encodes the data in the low six bits of each
byte. It ensures that binary data and non-ANSI character
data can be transmitted by e-mail without corruption. The
MIME specification defines the Base64 encoding method.
ColdFusion does not have a Base64 data type; it processes
Base64 encoded data as string data. ColdFusion provides
these functions that convert among string data, binary data,
and Base64 encoded string data:
| Function |
Description |
| ToBase64 |
Converts string and binary
data to Base64 encoded data. |
| ToBinary |
Converts Base64 encoded
data to binary data. |
| ToString |
Converts most simple
data types to string data. It can convert numbers, date-time
objects, and Boolean values. (It converts date-time
objects to ODBC timestamp strings.) It cannot convert
binary data that includes bytes that are not printable
characters. |
The ToString
function cannot convert Base64 encoded data directly to
an unencoded string. To convert Base64 encoded data that
was originally a string back to a readable string, first
use the ToBinary
function to convert the Base64 data into binary format.
Then use the ToString
function to convert the binary data to string. For example,
the following two lines print the same results:
<cfoutput>This is a test</cfoutput>
<cfoutput>#tostring(tobinary(tobase64("This is a test")))#</cfoutput>
Do not use binary data or Base64 data directly in ColdFusion
expressions.
Complex Data Types
Arrays, structures, and queries are ColdFusion built-in
complex data types. Structures and queries are sometimes
referred to as objects, as they are containers for data,
not individual data values. For details on complex data
types and their use, see Developing ColdFusion Applications.
Arrays
Arrays are tables of objects or data that can be indexed.
To create an array and specify its initial dimensions, use
the ColdFusion ArrayNew
function. For example, the following line creates an empty
two-dimensional array:
<cfset myarray=ArrayNew(2)>
Elements stored in an array are referenced as follows:
<cfset myarray[1][2]=Now()>
Although the ArrayNew function can only create up to three-dimensional
arrays directly, there is no limit on array size or maximum
dimension. To create arrays with more than three dimensions,
create arrays of arrays.
After you create an array, you can use functions or direct
references to manipulate its contents. When you assign an
existing array to a new variable, ColdFusion creates a new
array and copies the old array's contents to the new array.
The following example creates a copy of the original array:
Structures
You can use structures to create and maintain key-value
pairs, to refer to related string values as a unit, or to
create associative arrays. To create a structure, use the
ColdFusion StructNew
function. For example, the following line creates a new,
empty structure called depts:
<cfset depts=Structnew()>
After you create a structure, you can use functions or
direct references to manipulate its contents, including
adding key/value pairs.
You can use either of the following methods to reference
elements stored in a structure:
- StructureName.KeyName
- StructureName["KeyName"]
The following code shows examples of these methods:
depts.John="Sales"
depts["John Doe"]="Sales"
When you assign an existing structure to a new variable,
ColdFusion does not create a new structure. Instead,
the new variable accesses the same data (location) in memory
as the original structure variable. One way of expressing
this is to say that both variables are references to the
same object.
For example, the following code creates a new variable
myStructure2 that references the same structure as the myStructure
variable:
<CFSET myStructure2=myStructure>
When you change the contents of myStructure2, you also
change the contents of myStructure. To copy the contents
of a structure, use the ColdFusion Duplicate
function, which copies the contents of structures and other
complex data types.
Structure key names can be the names of structures or arrays.
This enables you to create arbitrarily complex structures.
Queries
A query object, often referred to as a query, is a complex
ColdFusion data type. The following ColdFusion tags can
create query objects:
- cfquery
- cfdirectory
- chttp
- cfldap
- cfpop
- cfprocresult
In these tags, the name
attribute specifies the query object's variable name. The
QueryNew function
also creates queries.
When you assign a query to a new variable, ColdFusion does
not copy the query object. Instead, both names
point to the same record set data. For example, the following
code creates a new variable myQuery2 that references the
same record set as the myQuery variable.
<CFSET myQuery2 = myQuery>
If you make changes to data in myQuery, myQuery2 also shows
those changes.
You reference query columns by specifying the query name,
a period, and the column name; for example:
When you reference columns inside tags such as cfoutput
and cfloop, in
which you specify the query name in a tag attribute, you
do not have to specify the query name.
You can access query columns as if they were one-dimensional
arrays. For example, the following statement assigns the
contents of the second row of the Employee column in the
myQuery query to the variable myVar:
<CFSET myVar = myQuery.Employee[2]>
You cannot use this notation to add rows to a query; instead,
use the QueryAddRow
function.
Note: The scoping rules that apply to all
variables apply to queries. For more information on scoping,
see Scopes.
Working with structures and queries
Because structure variables and query variables are references
to objects, the following rules apply to both types of data.
When multiple variables refer to a structure or query object,
the object continues to exist as long as at least one reference
to the object exists. The following code shows how this
works:
<cfscript> depts = structnew();</cfscript>
<cfset newStructure=depts>
<cfset depts.John="Sales">
<cfset depts=0>
<cfoutput>
#newStructure.John#
#depts#
</cfoutput>
This example displays the following output:
Sales
0
After the <cfset depts=0> tag executes, the variable
depts does not refer to a structure; it is a simple variable
with the value 0. However, the variable newStructure still
refers to the original structure object.
You can give a query or structure a different scope by
assigning it to a new variable in the other scope. For example,
the following line creates a Server variable Server.SScopeQuery
using the local myquery variable:
<CFSET Server.SScopeQuery = myquery>
To clear the server scope query variable, reassign the
query object, as follows:
<CFSET Server.SScopeQuery = 0>
This deletes the reference to the object from the server
scope, but does not remove any other references that may
exist.
You can use the Duplicate
function to copy a structure or query object. Changes to
the copy do not affect the original.
| Passing
Variables to Custom Tags and Functions |
The following sections describe rules for how data gets
passed to custom tags and functions that are written in
CFML, and to CFX custom tags that are written in Java or
C++.
Passing Variables to CFML Custom Tags and Functions
When you pass a variable to a CFML custom tag as an attribute,
or to a custom function as an argument, the following rules
determine whether the custom tag or function receives its
own private copy of the variable or only gets a reference
to the calling page's variable:
- Simple variables and arrays are passed as copies of
the data. If your argument is an expression that contains
multiple simple variables, the result of the expression
evaluation is copied to the function or tag.
- Structures, queries, and cfobject
objects are passed as references to the object.
If the tag or function gets a copy of the calling page's
data, changes to the variable in the custom tag or function
do not change the value on of the variable on the calling
page. If the variable is passed by reference, changes to
the variable in the custom tag or function also change the
value of the variable in the calling page.
To pass a variable to a custom tag, you must surround the
variable name in pound signs. To pass a variable to a function,
do not surround the variable name in pound signs.
For example, the following code calls a custom function
using three Form variables:
<cfoutput>
TOTAL INTEREST: #TotalInterest(Form.Principal, Form.AnnualPercent,
Form.Months)#
</cfoutput>
The following example calls a custom tag using two variables,
MyString and MyArray:
<cf_testTag stringval=#MyString# arrayval=#MyArray#>
Passing Variables to CFX Tags
You cannot pass arrays, structures, or cfobject objects
to CFX tags. You can pass a query to a CFX tag by using
the query attribute
when calling the tag. ColdFusion normally converts simple
data types to strings when passing them to CFX tags; however,
the Java Request Interface getIntAttributs
method allows you to get a passed integer value.
Click here to continue.