Suppose a class, foo, has one static variable, bar. Is it possible to write PHP code that will create a new static variable, bar2, for the foo class at runtime?
1 Answer
No, it's not possible.
A static variable is, as its name says, allocated statically at compile time. It cannot be allocated during runtime, nor can it be deallocated (e.g.: unset) during runtime either.
Also, static variables are independent of the call stack.
You can read more on Wikipedia.
6 Comments
netcoder
@nikic: No they don't. A static local variable is one thing. But a static variable is still a static variable.
NikiC
@netcoder: I still think that your statement isn't entirely correct. Static variables in PHP aren't really about memory being allocated at compile time (which sounds already pretty strange if a context of an interpreted, dynamically types language, where neither compilation happens, nor data structures can be really allocated in advance (maybe the
zval may be preallocated...). But I revoked by downvoted as a +1 to pointing out that my code was incorrect.netcoder
@nikic: Whether the language is interpreted (PHP, Java, Python) or not (C, Assembly), a compiler is still involved. Compilation actually means "to put together".
NikiC
@netcoder: It's a term one can argue about. But even if you assume that compilation is anything that happens before the program is executed, then still static variables have plainly nothing to do with what you linked on wikipedia. I actually checked the PHP source and basically the only difference between creating a static and a non-static variable, is that it is put into a different hash table. There is absolutely no difference in the way the values are initialized or allocated (in both cases only a zval is allocated).
netcoder
@nikic: No matter what the source code says, the definition remains the same: it can't be allocated or deallocated during runtime. Besides, you use the term "compile time" yourself. ;-)
|
static Foo::bar2 = 'baz'?