PHP Static Methods Can Be Declared Without Static Keyword But Called Statically
Whenever I create a PHP class method that I intend to use statically, I declare it as such using the ‘static‘ keyword:
<?php
class MyClass {
static public myStaticMethod() {
//do something
}
}
…
and then invoke it like so:
<?php
...
MyClass::myStaticMethod();
...
Recently I wrote a method that was meant to be static - but i forgot to declare it as such with the static keyword. I did not notice. I even invoked it like any other static method and it worked fine. When I discovered this, I was a bit surprised to see it working.
It seems that, in PHP version 5.2.9 at least, static methods can be declared without static keyword but invoked statically.
The PHP docs say “Calling non-static methods statically generates an E_STRICT level warning. ” - so i suppose the definition of non-static is not about the keyword, more about whether or not it uses “$this” inside the method.
I had to write a little test to convince myself.
This has the following output:
I am using PHP Version 5.2.9 and am about to call a method statically:
Something
