I have a question regarding static function in php.
let's assume that I have a class
class test {
public function sayHi() {
echo 'hi';
}
}
if I do test::sayHi();
it works without a problem.
class test {
public static function sayHi() {
echo 'hi';
}
}
test::sayHi();
works as well.
What are the differences between first class and second class?
What is special about a static function?
Calling non-static methods statically generates an E_STRICT level warning.
In the first class,
sayHi()
is actually an instance method which you are calling as a static method and you get away with it becausesayHi()
never refers to$this
.Static functions are associated with the class, not an instance of the class. As such,
$this
is not available from a static context ($this
isn't pointing to any object).Simply, static functions function independently of the class where they belong.
$this means, this is an object of this class. It does not apply to static functions.
Entire difference is, you don't get
$this
supplied inside the static function. If you try to use$this
, you'll get aFatal error: Using $this when not in object context
.Well, okay, one other difference: an
E_STRICT
warning is generated by your first example.After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use
$this
operator to work on class functions. So I couldn't find a difference in them yet. :(In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.