静态函数,静态函数

我有一个关于 php 中静态函数的问题。

假设我有课

class test {
public function sayHi() {
echo 'hi';
}
}

如果我做 test::sayHi();它的工作没有问题。

class test {
public static function sayHi() {
echo 'hi';
}
}

test::sayHi();也可以。

头等舱和二等舱有什么区别?

静态函数有什么特别之处?

119711 次浏览

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.

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.

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

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

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'

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