Is there a way to UnDim Variable?

2019-08-31 00:49发布

I'm just wondering if there is a possibility to un-dim a variable.

Imagine this is my #include file that I'm using in ASP page

Dim MyVar
MyVar = "Hello World"
Response.write(MyVar)
'From now on I can not use Dim MyVar anymore as it throws an error
'I have tried
MyVar = Nothing
Set MyVar = Nothing
'But again, when you do
Dim MyVar
'It throws an error.

The reason for this is that I cannot use the same #INCLUDE file more than once per page. And yes, I do like using Option Explicit as it helps me to keep my code cleaner.

*) Edited: I see that it's not as clear as I wanted.

Imagine this is a "include.asp"

<%
Dim A
A=1
Response.Cookie("beer")=A
%>

Now the asp page:

<!--#include file="include.asp"-->
<%
'Now: I do not see whats in include above and I want to use variable A
Dim A
'And I get an error
'I also cannot use the same include again:
%>
<!--#include file="include.asp"-->

Do you see my point? If I would be able to UNDIM the A variable at the end of the Include, the problem would be solved.

2条回答
迷人小祖宗
2楼-- · 2019-08-31 01:36

No there is no way to "UnDim" a variable. Luckily you also don't need that.

Whenever you try to declare a variable twice in the same scope, you're already making a mistake. Consider it as helpful that the runtime does not let you.

The solution:

  • Don't work with global variables. Use functions, declare your variables there.
  • Don't include the same file more than once.
查看更多
Root(大扎)
3楼-- · 2019-08-31 01:37

I agree with Tomalak - I'm really not sure why you would need (or want) to include the same file twice (?)

It does seem to be a bad design philosophy, better to perhaps encapsulate the routines in the include file as functions or subroutines that can be called - no need to include twice.

Also, whilst you cannot undim, you can redim, but I don't want to encourage bad practices, given what you seem to be wanting to do.

You could use something like this instead of all that:

Include.asp:

 <%
 Function SetCookie(scVar, scVal)
     Response.cookie (scVar) = scVal
 End Function
 %>

The asp page:

 <!--#include file="include.asp"-->
<%
Dim A
A=1
SetCookie "Beer", A

A=1 ' This is kind of redundant in this code.

SetCookie "Beer", A
%>

However if you did want to use globals, and persist with including twice, you could do it this way by adding another include for globals.

Globals.asp:

 <%
 Dim globalVarA
 ...other global stuff here....
 %>

Include.asp:

<%
globalVarA=1
Response.Cookie("beer")=globalVarA
%>

Now the asp page:

<!--#include file="globals.asp"-->
<!--#include file="include.asp"-->
<%
Dim A
A=....something......
%>
<!--#include file="include.asp"-->
查看更多
登录 后发表回答