php static function

岁酱吖の 提交于 2019-11-26 12:52:50

问题


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?


回答1:


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




回答2:


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'



回答3:


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.




回答4:


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




回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/902909/php-static-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!