Search code examples
phpclassstaticmember

php static function


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?


Solution

  • 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).