| << 4.6.1- Local Variables | Chapter4 | 4.7.0- String Manipulation >> |
Script Level Variables
So, if variables created in procedures are local to the procedure that created them, how do you go aboutensuring that the value of one variable persists from one procedure to thenext, when you need it to? In other words, how do you extend the lifetimes ofyour variables? The answer comes in the form of scriptlevel variables, which are variables that are declared outsideprocedures.
The lifetime of a script level variable begins at the startof the script (or scripts in one page) and ends at the end of the script, andspans any procedures created within the script. In comparison, local variablescontained within a procedure are destroyed when the procedure is exited, andhence the memory space is saved. It's a good idea to use local variables wherepossible, because it makes things easier to read and helps to avoid bugs incode and above all improves performance.
Now let's see how we can amend our previous program toinclude a script level variable:
Try It Out – Using Script Level Variables
We're going to simply add a new script level variable tothis program and then display it from inside and outside the procedures.
1. Load up the previous program, local.asp, in your preferred ASP editor andadd the following lines in the following locations:
<HTML>
<HEAD>
<TITLE>UsingScript Level Variables</TITLE>
</HEAD>
<BODYBGCOLOR="white">
<%
strGlobal ="I'm a persistent script-level variable"
Response.WritestrGlobal
Sub Procedure_1
strDifferent ="Hi I'm strDifferent in Procedure 1"
Response.Writestrdifferent
Response.Write"<P>" & strGlobal & "</P>"
End Sub
Sub Procedure_2
strDifferent ="Hi I'm strDifferent in Procedure 2"
Response.Writestrdifferent
Response.Write"<P>" & strGlobal & "</P>"
End Sub
%>
<P>CallingProcedure 1 ...<I><%Procedure_1()%></I></P>
<P>CallingProcedure 2 ...<I><%Procedure_2()%></I></P>
<P>CallingProcedure 1 ...<I><%Procedure_1()%></I></P>
</BODY>
</HTML>
2. Saveit this time as global.asp
3. Open this page on your browser.
|
|
How It Works
We've not changed our original program much, other thanadding new text the sole addition is a script level variable, strGlobal. This variable is assigned the text "I'ma persistent script-level variable" and is then called at various pointsin the program:
strGlobal ="I'm a persistent script-level variable"
We first display this string from outside both procedures;the second time, from within procedure 1; the third time from within procedure2; and the final time from within procedure 1 again. Each time, the variable isdisplayed using the following code, so there's no trickery of any sort:
Response.Write"<P>" & strGlobal & "</P>"
The output shows how script level variables and localvariables can be used side by side in any ASP program.
| << 4.6.1- Local Variables | Chapter4 | 4.7.0- String Manipulation >> |

RSS

