What is the difference between these two pieces of code?
class something {
static function doit() {
echo 'hello world';
}
}
something::doit();
and the same but without the static keyword
class something {
function doit() {
echo 'hello world';
}
}
something::doit();
They both work the same is it better to use the static keywords? Am i right in understanding that it doesn't instantiate the class if you use the static method?
Your second example is wrong. Using a static method does not create an instance of the class. Your second example should look like this:
The difference is that static functions can be used without having to create an instance of the class.
Have a look at this great PHP OOP beginner tutorial here. It explains in more detail with an example under the Static Properties and Methods section.
Second bit shouldn't work as you should call it by
Static functions allows you to call a function within a class without consturcting it. So basically if you have a class to handle users, so a function that logs the user in should be a static function, as in the constructor of that class you will probably gather the user information and you cannot do so without logging him in.
In addition to the other valid answers, the reason for the 2nd example working is also due to a quirk in how PHP handles objects and calls (Besides PHP 4 compatibility). Calling a non-
static
declared method statically from within another instance will let you access class methods on other classes as if they were local. To understand, let's take an example:Did you see what happened there? Because you called the
A::foo()
method from within another class's instance, PHP treated the call as if it was on the same instance. Note that there is no relationship betweenA
andB
other than the fact thatB
callsA
. WithinA->foo()
, if we did$this instanceof A
(or$this instanceof self
), it would fail and return false! Quite unusual...Now, I first thought it was a bug, but after reporting it, it's apparently as designed. It's even in the docs.
Note that this will not work with
E_STRICT
mode enabled. It also will not work if you declare a method asstatic
.The second example is technically incorrect - if you turn on E_STRICT error reporting you'll see that PHP is actually throwing an error.
In other words, it's being nice and letting you call the function anyway.
Static methods should be declared static for minimum two reasons:
a) when using
E_STRICT
error_reporting, calling non static method as static will generate error:Strict standards: Non-static method something::doit() should not be called statically
b) based on keyword
static
some IDE's filter method possible to run at auto-complete.