Static variables in ASP.NET caught me off guard today. Then i became freaked out, because this means either i have a fundamental misunderstanding of static variables in the world of the web or ASP.NET does not act like i thought it would.
So in ASP.NET
public class MyClass {
public static bool myVar = true;
}
If ASPUserA sets MyClass.myVar = false every other user on the system would experience these changes. So, ASPUserB would have myVar = false. My Source: http://www.foliotek.com/devblog/avoid-static-variables-in-asp-net/
class MyClassPHP {
public static $myVar = false;
}
If PHPUserA sets MyClass::$myVar = true does this mean that every user on the system experiences these changes???
Thank you.
Upon further research i did this;
class MyClassPHP {
public static $myVar = 0;
}
Then i had users who went to a page do this
MyClassPHP::$myVar++;
echo MyClassPHP::$myVar;
It always was 1. No matter how many times i refreshed or simultaneous connections... WOHHH that was a great conclusion, or else i am screwed!!
ASP.NET update
Upon further research and testing things i found this.
public partial class MyPage : System.Web.UI.Page
{
public static int myInt = 0;
protected void Page_PreInit(object sender, EventArgs e)
myInt++;
}
}
Then my page can display myInt.
Between the browsers (Firefox and chrome) the myInt was progressively higher as i refreshed the page. So this does not matter if your class is static. It only matters if you have static variables. They are application wide.
When running in IIS:
A static variable is not "page" specific. It is "AppDomain" specific. The only relation to the "page" would be the path (so to speak) of the variable (MyProject.MyPage.MyVariable for example). Because all users of your application are running in the same AppDomain (i.e. same IIS application folder), then they will all use the same static variable. So... eventually your users are going to see each each other's information since they are all sharing that one single static variable.
PHP however tracks statics PER USER INSTANCE, so I guess you could call them "safer from the singleton dangerzone".