php static function

PhpClassStaticMember

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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.

class test {
    public function sayHi($hi = "Hi") {
        $this->hi = $hi;
        return $this->hi;
    }
}
class test1 {
    public static function sayHi($hi) {
        $hi = "Hi";
        return $hi;
    }
}

//  Test
$mytest = new test();
print $mytest->sayHi('hello');  // returns 'hello'
print test1::sayHi('hello');    //  returns 'Hi'

Solution 3 - Php

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.

Solution 4 - Php

Calling non-static methods statically generates an E_STRICT level warning.

Solution 5 - Php

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.

Solution 6 - Php

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. :(

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMoonView Question on Stackoverflow
Solution 1 - PhpJonathan FinglandView Answer on Stackoverflow
Solution 2 - Phpuser2132859View Answer on Stackoverflow
Solution 3 - PhpchaosView Answer on Stackoverflow
Solution 4 - Phpuser2598812View Answer on Stackoverflow
Solution 5 - PhpCzimiView Answer on Stackoverflow
Solution 6 - PhpyogeshView Answer on Stackoverflow