当前位置:首页 > PHP教程 > php应用 > 列表

区别PHP中new self() 和 new static()

发布:smiling 来源: PHP粉丝网  添加日期:2022-06-21 08:22:05 浏览: 评论:0 

PHP中new self() 和 new static() 的区别

new static() 是在php5.3版本引入的新特性

new static 和 new self() 都是 new 一个对象

直接看代码:

  1. class Father 
  2.  
  3. { 
  4.  
  5.     public function getNewFather() 
  6.  
  7.     { 
  8.  
  9.         return new self(); 
  10.  
  11.     } 
  12.  
  13.     
  14.  
  15.     public function getNewCaller() 
  16.  
  17.     { 
  18.  
  19.         return new static(); 
  20.  
  21.     } 
  22.  
  23. } 
  24.  
  25.     
  26.  
  27. $f = new Father(); 
  28.  
  29.     
  30.  
  31. var_dump(get_class($f->getNewFather())); // Father 
  32.  
  33. var_dump(get_class($f->getNewCaller())); // Father 

getNewFather和getNewCaller 都是返回的 Father 这个实列

到这里貌似 new self() 还是 new static() 是没有区别的

接着看下面的示例:

  1. class Sun1 extends Father{ 
  2.  
  3.     
  4.  
  5. } 
  6.  
  7.     
  8.  
  9. $sun1 = new Sun1(); 
  10.  
  11.     
  12.  
  13. var_dump($sun1->getNewFather()); // object(Father)#4 (0) { } 
  14.  
  15. var_dump($sun1->getNewCaller()); // object(Sun1)#4 (0) { } 

getNewFather 返回的是Father的实列,

getNewCaller 返回的是调用者的实列

他们的区别只有在继承中才能体现出来、如果没有任何继承、那么二者没有任何区别

new self() 返回的实列是不会变的,无论谁去调用,都返回的一个类的实列,

new static则是由调用者决定的。

Tags: self static

分享到: