Using Variables


Now that you've had the chance to use some basic functions, it's time to introduce variables. Variables are an important part of just about every programming language, and CFML is no exception. A variable is a container that stores information in memory on the server. Variables are named, and the contents of the container are accessed via that name. Let's look at a simple example. Type the code in Listing 8.4 into a new file (feel free to use your own name instead of mine), save it as hello4.cfm, and browse it. You should see a display similar to the one shown in Figure 8.7.

Listing 8.4. hello4.cfm
 <html> <head>  <title>Hello 4</title> </head> <body> <cfset FirstName="Ben"> <cfoutput> Hello #FirstName#, and welcome to ColdFusion! </cfoutput> </body> </html> 

Figure 8.7. Variables are replaced by their contents when content is generated.


This code is similar to the previous code listings. It starts with plain HTML, which is sent to the client as is. Then a new tag is used, <cfset>:

 <cfset FirstName="Ben"> 

<cfset> is used to set variables. Here, a variable named FirstName is created, and a value of Ben is stored in it. After it's created, that variable will exist until the page has finished processing and can be used, as seen in the next line of code:

 Hello #FirstName#, and welcome to ColdFusion! 

This line of code was placed in a <cfoutput> block so ColdFusion will know to replace #FirstName# with the contents of FirstName. The generated output is then:

 Hello Ben, and welcome to ColdFusion! 

Variables can be used as many times as necessary, as long as they exist. Try moving the <cfset> statement after the <cfoutput> block, or delete it altogether. Executing the page now will generate an error, similar to the one seen in Figure 8.8. This error message is telling you that you referred to (tried to access) a variable that doesn't exist. The error message includes the name of the variable that caused the problem, as well as the line and column in your code, to help you find and fix the problem easily. More often than not, this kind of error is caused by typos.

Figure 8.8. ColdFusion produces an error if a referenced variable doesn't exist.


If the error message doesnt contain line numbers (or displays less detail than seen in Figure 8.8), you'll need to access the ColdFusion Administrator (as explained in Chapter 3), go to the Debugging Settings page, and turn on Enable Robust Exception Information.


Regular variables exist only in the page that creates them. If you define a variable named FirstName in one page, you cant use it in another page unless you explicitly pass it to that page (see Chapter 10). An exception to this rule does exist. In Chapter 17, "Working with Sessions," you learn how to create and use variables that persist across requests. (Each page access is known as a request.)


Here is a new version of the code, this time using the variable FirstName six times. Save Listing 8.5 as hello5.cfm, and then try this listing for yourself (feel free to replace my name with your own). The output is shown in Figure 8.9.

Listing 8.5. hello5.cfm
 <html>     <head>      <title>Hello 5</title>     </head>     <body>     <cfset firstName="ben">     <cfoutput>     Hello #firstName#, and welcome to ColdFusion!<p>     Your name in uppercase: #UCase(firstName)#<br>     Your name in lowercase: #LCase(firstName)#<br>     Your name in reverse: #Reverse(firstName)#<br>     Characters in your name: #Len(firstName)#<br>     Your name 3 times: #RepeatString(firstName, 3)#<br>     </cfoutput>     </body>     </html> 

Figure 8.9. There is no limit to the number of functions that can be used in one page, which enables you to render content as you see fit.


Let's take a look at the above code. A <cfset> is used to create a variable named FirstName. That variable is used once by itself (the Hello message), and then five times with functions. UCase() converts a string to uppercase, LCase() converts a string to lowercase, Reverse() reverses the string, Len() returns the length of a string (the number of characters in it), and RepeatString() repeats a string a specified number of times.

But functions such as UCase() don't truly convert strings; instead, they return converted strings. The difference is subtle but important. Look at the following line of code:

 Your name in uppercase: #UCase(firstName)# 

UCase() returns FirstName converted to uppercase, but the contents of FirstName itself are intact and are not converted to anything at all. FirstName was not modified; a copy was made and modified instead, and that copy was returned. To save the uppercase FirstName to a variable, you must do something like this:

 <CFSET UpperFirstName=UCase(FirstName)> 

Here a new variable, UpperFirstName, is created. UpperFirstName is assigned the value that is returned by UCase(FirstName), the uppercase FirstName. And this new variable can be used like any other variable, and as often as necessary. Listing 8.6 is a modified version of the Listing 8.5. Try it for yourselfthe output will be exactly the same as in Figure 8.9.

Listing 8.6. hello6.cfm
 <html> <head>  <title>Hello 6</title> </head> <body> <cfset firstName="ben"> <cfset upperFirstname=UCase(firstName)> <cfset lowerFirstname=LCase(firstName)> <cfset reverseFirstname=Reverse(firstName)> <cfset lenFirstName=Len(firstName)> <cfset repeatFirstName=RepeatString(firstName, 3)> <cfoutput> Hello #FirstName#, and welcome to ColdFusion!<p> Your name in uppercase: #upperFirstName#<br> Your name in lowercase: #lowerFirstName#<br> Your name in reverse: #reverseFirstName#<br> Characters in your name: #lenFirstName#<br> Your name 3 times: #repeatFirstName#<br> </cfoutput> </body> </html> 

This code deserves a closer look. Six <cfset> tags now exist, and six variables are created. The first creates the firstName variable, just like in the previous examples. The next creates a new variable named upperFirstName, which contains the uppercase version of firstName. And then lowerFirstName, reverseFirstName, lenFirstName, and repeatFirstName are each created with additional <cfset> statements.

The <cfoutput> block here contains no functions at all. Rather, it just displays the contents of the variables that were just created. In this particular listing there is actually little value in doing this, aside from the fact that the code is a bit more organized this way. The real benefit in saving function output to variables is realized when a function is used many times in a single page. Then, instead of using the same function over and over, you can use it once, save the output to a variable, and just use that variable instead.

One important point to note here is that variables can be overwritten. Look at the following code snippet:

 <cfset firstName="Ben"> <cfset firstName="Nate"> 

Here, firstName is set to Ben and then set again to Nate. Variables can be overwritten as often as necessary, and whatever the current value is when accessed (displayed, or passed to other functions), that's the value that will be used.

Knowing that, what do you think the following line of code does?

 <cfset firstName=UCase(FirstName)> 

This is an example of variable overwriting, but here the variable being overwritten is the variable itself. I mentioned earlier that functions such as UCase() don't convert text; they return a converted copy. So how could you really convert text? By using code such as the line just shown. <cfset firstName=UCase(firstName)> sets firstName to the uppercase version of firstName, effectively overwriting itself with the converted value.

Variable Naming

This would be a good place to discuss variable naming. When you create a variable you get to name it, and the choice of names is up to you. However, you need to know a few rules about variable naming:

  • Variable names can contain alphanumeric characters but can't begin with a number (so result12 is okay, but 4tHResult is not).

  • Variable names can't contain spaces. If you need to separate words, use underscores (for example, monthly_sales_figures instead of monthly sales figures).

  • Aside from the underscore, non-alphanumeric characters can't be used in variable names (so Sales!, SSN#, and first-name are all invalid).

  • Variable names are case insensitive (FirstName is the same as FIRSTNAME, which is the same as firstname, which is the same as firstName).

Other than that, you can be as creative as necessary with your names. Pick any variable name you want; just be careful not to overwrite existing variables by mistake.

TIP

Avoid the use of abbreviated variable names, such as fn or c. Although these are valid names, what they stand for is not apparent just by looking at them. Yes, fn is less keystrokes than FirstName, but the first time you (or someone else) must stare at the code trying to figure out what a variable is for, you'll regret saving that little bit of time. As a rule, make variable names descriptive.


Using Prefixes

ColdFusion supports many variable types, and you'll become very familiar with them as you work through this book. For example, local variables (the type you just created) are a variable type. Submitted form fields are a variable type, as are many others.

ColdFusion variables can be referenced in two ways:

  • The variable name itself.

  • The variable name with the type as a prefix.

For example, the variable firstName that you used a little earlier is a local variable (type VARIABLES). That variable can be referred to as firstName (as you did previously) and as VARIABLES.firstName. Both are valid, and both will work (you can try editing file hello6.cfm to use the VARIABLES prefix to try this).

So, should you use prefixes? Well, there are pros and cons. Here are the pros:

  • Using prefixes improves performance. ColdFusion will have less work to do finding the variable you are referring to if you explicitly provide the full name (including the prefix).

  • If multiple variables exist with the same name but are of different types, the only way to be 100 percent sure that you'll get the variable you want is to use the prefix.

As for the cons, there is just one:

  • If you omit the prefix, multiple variable types will be accessible (perhaps form fields and URL parameters, which are discussed in the following chapters). If you provide the type prefix, you restrict access to the specified type, and although this does prevent ambiguity (as just explained), it does make your code a little less reusable.

The choice is yours, and there is no real right or wrong. You can use prefixes if you see fit, and not use them if not. If you don't specify the prefix, ColdFusion will find the variable for you. And if multiple variables of the same name do exist (with differing types) then a predefined order of precedence is used. (Don't worry if these types are not familiar yet, they will become familiar soon enough, and you can refer to this list when necessary.) Here is the order:

  • Query results

  • Function ARGUMENTS

  • Local variables (VARIABLES)

  • CGI variables

  • FILE variables

  • URL parameters

  • FORM fields

  • COOKIE values

  • CLIENT variables

In other words, if you refer to #firstName# (without specifying a prefix) and that variable exists both as a local variable (VARIABLES.firstName) and as a FORM field (FORM.firstName), VARIABLES.firstName will be used automatically.

NOTE

An exception to this does exist. Some ColdFusion variable types must always be accessed with an explicit prefix; these are covered in later chapters.




Macromedia Coldfusion MX 7 Web Application Construction Kit
Macromedia Coldfusion MX 7 Web Application Construction Kit
ISBN: 321223675
EAN: N/A
Year: 2006
Pages: 282

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net