As we all know, static methods can be called without instantiating the class. So I wonder if static methods will be loaded into memory before I use them. If that, in my view, I should use more intance methods instead of too many static methods. Anyone advice? I am not familiar with the underlying mechanism of PHP.
A static method is just a regular function with a fancy name (and restricted access if it is not public
).
Static methods are not OOP, they are procedural code in disguise.
Should I avoid using too many static methods in PHP?
It depends how many do you think are "too many". For pure OOP code, one static method is already "too many". But sometimes it's unavoidable (read "easier") to write a static method for some functionality.
So I wonder if static methods will be loaded into memory before I use them.
No matter if you run a PHP script using the CLI or it is invoked through the web server to serve a web page, the text of the script is loaded into memory and compiled. If the compilation is successful (i.e. there are no syntax errors), the interpreter starts executing it.
Everything that is defined in the script is already in memory at this moment, but only the items defined in the main script. The inclusion statements (include
, include_once
, require
, require_once
) are not processed during the compilation phase.
The file referred by a include
statement is loaded in memory, compiled and executed when, and if, the include
statement is reached during the execution of the script. The entire content of the included file is loaded, parsed and converted to opcodes, no matter if it contains functions, classes or global code. There is no differences between instance methods and static methods from this point of view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With