I'm working on an old application that often declares variables that seem to be global, using identifiers likely to be used elsewhere.
When writing a function, some parameters happen to have the same name as those global variables, and it is hardly avoidable, because one doesn't know if that identifier is already in use by one of these global variables, or it might be, but within a script that ends up not being called.
SomeRandomPage.asp :
foo = "bar" ' Not sure if it's declared with Dim or not
MyFunction.asp :
Function MyFunction(foo) ' Same name as global variable "foo"
foo = foo & "123"
MyFunction = foo
End Function
If the function affects a value to that parameter, the global variable also appears to be modified, like VB Script didn't care about variable scopes at all.
Dim bang : bang = "hello"
Response.Write foo ' "foo"
bang = MyFunction(bang)
Response.Write foo ' "hello123"
The solution I was suggested is to declare local variables in my function using Dim
, copying my parameters into those local variables, and using those local variables instead of the parameter.
Function MyFunction(foo)
Dim localFoo : localFoo = foo
localFoo = localFoo & "123"
MyFunction = localFoo
End Function
As poor as VB Script can be, I can't imagine that this dirty method would be the only solution to avoid this global variable overwriting behaviour.
So my question is : how can I prevent global variables from being overwritten by assigning values to function parameters that happen to have the same name ?