<%I've found it makes it easier for me to debug my code.
Option Explicit
Dim Var1, Var2, Var3
%>
If you do declare your variables, do it first thing at the top of the page for your global variables. If you use function or subroutine variables, you can declare those inside the subroutine of function in which you use them.
The main advantage of declaring variables is that it makes it easier to debug your code, because if you misspell a variable it will show up as undeclared. Declaring your variables has an added effect, usually unknown to beginning programmers.
Say you have a subroutine the figures out the values of something:
<%Now you would think the value of z would be accessible to the rest of the page, but it won't unless you've declared it as a global variable outside the subroutine. So if you try this:
Sub DoSomething
x = 1
y = 2
z = x + y
End Sub
%>
<%You won't see anything, because the value of z won't come out of the subroutine. You have to do it like this:
Call DoSomething
response.write(z)
%>
<%In this example, since z has been declared as a global variable, it will persist out of the function and be accessible to the rest of you code.
Dim z
Call DoSomething
response.write(z)
%>
I remember practically pulling my hair out the first time I used a subroutine to concatenate a string and then couldn't get the string to print!
There is another way to accomplish this without using a script level Dim statement; you can declare the subroutine as Public.
<%So here are the rules summed up:
Public Sub DoSomething
x = 1
y = 2
z = x + y
End Sub
%>
- Variables in Private subroutines and functions are available only to that function or subroutine
- Variables in Public subroutines and functions are available to the entire script
- Variables declared at the script level are available to the entire script
- Variables declared at the subroutein or function level are available only within that subroutine or function
No comments:
Post a Comment