php static method,php 类方法用static::hello(); 等同于 $this-hello();吗?
自 PHP 5.3.0 起,PHP 增加了一個叫做后期靜態綁定的功能,用于在繼承范圍內引用靜態調用的類。
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
以上例程會輸出:
A
可以實現在父類中調用子類的靜態方法的作用。
后期靜態綁定本想通過引入一個新的關鍵字表示運行時最初調用的類來繞過限制。簡單地說,這個關鍵字能夠讓你在上述例子中調用 test() 時引用的類是 B 而不是 A。最終決定不引入新的關鍵字,而是使用已經預留的 static 關鍵字。
在非靜態環境下,所調用的類即為該對象實例所屬的類。由于 $this-> 會在同一作用范圍內嘗試調用私有方法,而 static:: 則可能給出不同結果。另一個區別是 static:: 只能用于靜態屬性。
class A {
private function foo() {
echo "success!\n";
}
public function test() {
$this->foo();
static::foo();
}
}
class B extends A {
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
class C extends A {
private function foo() {
/* original method is replaced; the scope of the new one is C */
}
}
$b = new B();
$b->test();
$c = new C();
$c->test(); //fails
以上例程會輸出:
success!
success!
success!
Fatal error: Call to private method C::foo() from context 'A' in /tmp/test.php on line 9
總結
以上是生活随笔為你收集整理的php static method,php 类方法用static::hello(); 等同于 $this-hello();吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 8 jit,PHP JIT 是什
- 下一篇: php读取客户机本地时间,PHP如何获取