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

WBOY
發布: 2016-05-16 09:00:14
原創
2719 人瀏覽過

在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關鍵字允許函數能夠在執行時間動態綁定類別中的方法。

相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!