I have been wondering for a while already how does static variables work regarding memory use and should that even be really considered?
I understand that static variables will only use up one area of memory, doesn’t matter how many instances there are of the class itself. So in this sense, it should be wise to use static variables for wise memory consumption too, right? But I’ve never stumbled across anyone talking about the memory usage of static variables (only that you can share the data with different instances).
For example:
class Something () {
static $DB = null;
__construct ($DB) {
$this->DB = $DB;
}
}
If I would create 10 instances of this class, then it would generate less memory usage, than with non-static $DB-variable, right?
And if it is so, is the effect so small, it doesn’t really matter?
No you shouldn’t worry about
statics for that reason.The reason you have to worry about the use of
staticis the fact that you cannot unit test your code anymore and you have tightly coupled classes and code toSomething::DB(i.e. the Something class) and you are working with global state.Also check out an previous answer by me about how to handle those “global” instances: Which is the best practice to access config inside a function?