

|
|
Variables in CFML; Assigning Data to VariablesTo work with variables and the data they contain you must first be able to assign values to them. Assigning Simple ValuesNumeric and Boolean values can be assigned directly to variables. Here are some examples: <cfset foo = 15> String values must be quoted to differentiate them from variable names: <cfset foo = "My String"> Finally, values in variables can be assigned directly to other variables or the results of expressions as in the following examples: <cfset fee = foo> Make sure to read the section on Assignment by Value and Reference for important information regarding this. Escaping Special CharactersSpecial characters, such as the pound sign ("#") and the double quote are used to distinguish variables from other CFML code. If you wish to use them as part of the variable data you must escape them. This tells ColdFusion to treat the special character(s) as part of the data, not part of the code.
<cfset foo = "##FFFFFF"> The same technique is used for double quotes as in the following: <cfset foo = "He said ""I trust you"" but I didn't believe him."> Pound Signs in AssignmentsPound signs ("#"), also sometimes called "Hash Marks" are used to indicate a CFML variable within a string (or, generally, within a CFOUTPUT). It's a common mistake to use pound signs more often than needed. The following example shows an example of how you'd use pound signs in an assignment.: <cfset foo = "My String"> Pounds signs are only needed when you need to use a CFML variable within a string. In the following examples the pound signs are not required: <cfset foo = #Len(Foo)#> ExpressionsAny CFML expression can be used as the "value" for a variable. The variable will then contain the results of the expression. For example all of the following are legal variable assignments: <cfset foo = 15> The ampersand ("&") can used to concatenate strings instead of using pound signs to delimit them as in: <cfset foo = "My String"> All CFML functions result in values that can be directly assigned to variables: <cfset foo = now()> Nulls (or the Lack of Them)
In CFML you can approach the concept somewhat poorly with the "empty string" as in: <cfset foo = ""> The above code will create the variable "foo" but assign it no obvious value. This is not the same as "null" (which specifically indicates no value) but comes close enough for most purposes. In most cases ColdFusion will convert nulls (as returned from a database call for example) to the empty string. However in some cases (as when you convert a query column to an array or to a list) ColdFusion simply eliminates null cells. You should be aware of this when working with nulls from external sources. |