首頁  >  文章  >  後端開發  >  php物件導向程式設計self和static的區別_php技巧

php物件導向程式設計self和static的區別_php技巧

WBOY
WBOY原創
2016-05-16 09:00:142721瀏覽

在php的物件導向程式設計中,總是會遇到

class test{
 public static function test(){
  self::func();

  static::func();
 }

 public static function func(){}
}

可你知道self和static的差別?

其實差別很簡單,只要寫幾個demo就能懂:

demo for self:

class car
{
 public static function model(){
  self::getmodel();
 }

 protected static function getmodel(){
  echo "this is a car model";
 }
}

car::model();

class taxi extends car
{
 protected static function getmodel(){
  echo "this is a taxi model";
 }
}

taxi::model();
得到輸出

this is a car model
this is a car model

可以發現,self在子類別中還是會呼叫父類別的方法

demo for static

class car
{
 public static function model(){
  static::getmodel();
 }

 protected static function getmodel(){
  echo "this is a car model";
 }
}

car::model();

class taxi extends car
{
 protected static function getmodel(){
  echo "this is a taxi model";
 }
}

taxi::model();

得到輸出

This is a car model
This is a Taxi model

可以看到,在呼叫static,子類別即使呼叫的是父類別的方法,但是父類別方法中呼叫的方法還會是子類別的方法(好繞嘴。)

在php5.3版本以前,static和self還是有一點差別,具體是什麼,畢竟都是7版的天下了。就不去了解了。

總結呢:self只能引用目前類別中的方法,而static關鍵字允許函數能夠在執行時間動態綁定類別中的方法。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn