2

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?

6
  • Can you elaborate on why exactly you are wanting to do this? Commented Apr 7, 2011 at 20:53
  • random guess: static Foo::bar2 = 'baz'? Commented Apr 7, 2011 at 20:53
  • @TaylorOtwell: For convenience. If it was possible, I could create globally accessed objects dynamically. Commented Apr 7, 2011 at 20:57
  • 2
    @johnjohn: I think you really don't want to do that (using globals). It's pretty much an anti-pattern. It brings more harm than good. Commented Apr 7, 2011 at 21:00
  • @johnjohn netcoder is right - you should never need to. Note, however, that you could have a static associative array and use that instead. Commented Apr 7, 2011 at 21:03

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

6 Comments

@nikic: No they don't. A static local variable is one thing. But a static variable is still a static variable.
@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.
@nikic: Whether the language is interpreted (PHP, Java, Python) or not (C, Assembly), a compiler is still involved. Compilation actually means "to put together".
@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).
@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. ;-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.