PHP 面向對象 static 和 self 的區別

1、前言php

php是世界上最好的語言spa

php從面向過程走到如今成熟的面向對象體系, 在php面向對象中,靜態變量的調用咱們能夠用這兩個self::method和 static::method, 可是不少童鞋迷惑,不理解self::method和static::method有什麼區別,下面給出兩個例子一看究竟:code

例子1:對象

 1 class Car {  2     public static function model()  3  {  4         self::getModel();  5  }  6     protected static function getModel()  7  {  8         echo "This is a car model";  9  } 10 } 11 Car::model(); //This is a car model
12 echo '<br />'; 13 Class Taxi extends Car { 14     protected static function getModel() 15  { 16         echo "This is a Taxi model"; 17  } 18 } 19 Taxi::model(); //This is a car model

總結: self::getModel()調用方法getModel(), 子類的方法getModel()實際意義上沒有重載父類的方法getModel().blog

例子2 :
get

 

 1 class Car {  2     public static function model()  3  {  4         static::getModel();  5  }  6     protected static function getModel()  7  {  8         echo "This is a car model";  9  } 10 } 11 Car::model();  //This is a car model
12 echo '<br />'; 13 Class Taxi extends Car { 14     protected static function getModel() 15  { 16         echo "This is a Taxi model"; 17  } 18 } 19 Taxi::model(); //This is a Taxi model

 

總結: self::getModel()調用方法getModel(), 子類的方法getModel()重載了父類的方法getModel().io

童鞋們,理解了嗎?function

若有疑惑,歡迎評論class

相關文章
相關標籤/搜索