GullyBoy GullyBoy - 1 month ago 6
PHP Question

PHP "Static" keyword is misleading its not retaining new value

ok im having a problem with the static keyword

according to w3wchools.com below


Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:


//w3school code below
function myTest() {
static $x = 0;
echo $x;
$x++;
myTest();
myTest();
myTest();
}


now what this will do is basically count 0,1,2 with a ++ incremental operator. fine it does what there definition of static describes it does

now if i do the same thing basically in another way with my code below...the $x does not increment it just stays at 0.

//my code version below
function myTest() {
static $x = 0;
echo $x;
$x + 1;
myTest();
myTest();
myTest();
}


these are basically doing the SAME thing in theory

w3schools version increments $x by 1 with ++ operator. increment means to add

my version adds 1 with + operator...and add means to add also

so is it safe to say that static only works for incremental operators
instead of basic math operators?

Answer

This has nothing to do with the static keyword. The code $x+1 does not change the value of $x at all, so it never increments. $x+=1 or $x = $x + 1 would have the effect you wanted.

Comments