July 28, 200818 yr Having a bit of a hard time figuring this out. function staticTest() { static $a = 0; echo $a; $a++; } staticTest(); staticTest(); staticTest(); If I run this I get 012 on appear, however I can't work out why. I know that static variables hold their value when they're not in execution but why does it ignore the following at the top of the function, how would I change this variable if I wanted to? static $a = 0; Any help to let me get my head around this would be much appreciated . Also should I create every script I make as an OO script? I've got no problem with OO but I can't see how it would be advantageous when linear scripting works well enough?
July 29, 200818 yr Cabbage, You know that static variables hold their value when they're not in execution. So the piece of code below runs only once - when the function and it's static variable are defined and before the function is ever called. static $a = 0; If you wanted to change the value of $a within the function you would write this: $a = 'new value'; You are changing the value of $a already within your function with this line: $a++; This will just increment $a by 1, of course. Also should I create every script I make as an OO script? I've got no problem with OO but I can't see how it would be advantageous when linear scripting works well enough? The disadvantage of OO scripts is that scripts written for PHP5 sometimes won't work with PHP4 (e.g. PHP4 doesn't do static variables within classes). But it's really a question of taste, if the linear scripting works well enough then you may as well keep it. OO scripts are most useful if you are going to be creating some functionality that will be reused for several different applications.
Create an account or sign in to comment