tags:

views:

997

answers:

3

Hi,

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 differences between first class and second class?

what is special about static function?

+2  A: 

Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.

Well, okay, one other difference: an E_STRICT warning is generated by your first example.

chaos
+1  A: 

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.

Czimi
+7  A: 

In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() 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)

Jonathan Fingland
Now static calling of non-static methods works but is deprecated. Be careful using this syntax for instance methods!
Jet