In php5 static variables in functions behave a little differently when the functions are member functions of a class. The problems start when the inheritance starts copying out functions into the child function table hashes. For instance, consider the following bit of code :
<?php
class A {
function f()
{
static $a = 10;
$a++;
echo __CLASS__.": $a\n";
}
}
class B extends A { }
$a = new A();
$b = new B();
$a->f();
$b->f();
?>
Now, I'd assumed that it would obviously produce 11 12 as the output. Sort of ran into this while messing around with the zend_op_array reference counting code. The static members are killed off before the reference is checked.
gopal@knockturn:/tmp$ /opt/php5/bin/php -q test.php A: 11 A: 11
I definitely was slightly freaked and wrote up an almost identical bit of C++ code to just test out my preconceptions about static variables.
#include <stdio.h>
class A
{
public:
void f() {
static int a = 10;
a++;
printf("A: %d\n", a);
}
};
class B : public A {};
int main()
{
A a;
B b;
a.f();
b.f();
}
But static variables inside a function in C++ behave identical to whether it was declared inside a class or outside. There seems to be no special handling for member functions unlike what php shows.
gopal@knockturn:/tmp$ ./static-test A: 11 A: 12
I am not enough of a dynamic language geek to decide which one's the right way to do it. Actually if I really had my way, there wouldn't be any static variables in functions at all. They're actually too much like global variables in terms of life-time.
Anyway, using a class static should make it behave like C++.
--In theory, there is no difference between theory and practice.
In practice, there is.
