Moo*_*oon 106 php static class member
我有一个关于php中的静态函数的问题.
我们假设我有一堂课
class test {
public function sayHi() {
echo 'hi';
}
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做test::sayHi();没有问题.
class test {
public static function sayHi() {
echo 'hi';
}
}
Run Code Online (Sandbox Code Playgroud)
test::sayHi(); 也有效.
头等舱和二等舱有什么区别?
静态函数有什么特别之处?
Jon*_*and 152
在第一个类中,sayHi()实际上是一个实例方法,您将其作为一个静态方法调用,并且因为sayHi()从未引用过它而侥幸逃脱$this.
静态函数与类关联,而不是类的实例.因此,$this静态上下文不可用($this不指向任何对象).
小智 22
简单地说,静态函数的功能与它们所属的类无关.
$这意味着,这是这个类的一个对象.它不适用于静态函数.
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'
Run Code Online (Sandbox Code Playgroud)
cha*_*aos 20
完全不同的是,你没有$this在静态函数内部提供.如果你尝试使用$this,你会得到一个Fatal error: Using $this when not in object context.
好吧,还有,另一个区别是:E_STRICT你的第一个例子会产生一个警告.
| 归档时间: |
|
| 查看次数: |
112023 次 |
| 最近记录: |