PHP中new static()與new self()的區別異同分析

self - 就是這個類,是代碼段裏面的這個類。 php

static - PHP 5.3加進來的只得是當前這個類,有點像$this的意思,從堆內存中提取出來,訪問的是當前實例化的那個類,那麼 static 表明的就是那個類。 測試

仍是看看老外的專業解釋吧: this

self refers to the same class whose method the new operation takes place in. code

static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on. 內存

In the following example, B inherits both methods from A. self is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see  get_called_class() ). get

class A {
  public static function get_self() {
    return new self();
  }
 
  public static function get_static() {
    return new static();
  }
}
 
class B extends A {}
 
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_static()); // A




這個例子基本上一看就懂了吧。 string

原理了解了,可是問題尚未解決,如何解決掉 return new static($val); 這個問題呢? it

其實也簡單就是用 get_class($this); 代碼以下: io

class A {
  public function create1() {
    $class = get_class($this);
    return new $class();
  }
  public function create2() {
    return new static();
  }
}
 
class B extends A {
 
}
 
$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));
 
/*
The result 
string(1) "B"
string(1) "B"
*/




感興趣的朋友能夠動手測試一下示例代碼,相信會有新的收穫! function

相關文章
相關標籤/搜索