self parent this 區別

this是指向當前對象的指針(可以看成C裏面的指針),self是指向當前類的指針,parent是指向父類的指針。
<一>this例
 class name  //建立了一個名爲name的類 
{ 
     private $name;    //定義屬性,私有 
     //定義構造函數,用於初始化賦值  
    function __construct( $name ) 
     { 
          $this->name = $name; //這裏已經使用了this指針語句① 
     } 
     //析構函數 
     function __destruct(){} 
     //打印用戶名成員函數 
     fuction printname() 
     { 
          print( $this->name ); //再次使用了this指針語句②
     } 
   } 
   $obj1 = new name( "PBPHome" );//實例化對象語句③ 
   $obj1->printname(); 
 Note:如果子類中定義了構造函數則不會隱式調用其父類的構造函數。要執行父類的構造函數,需要在子類的構造函數中調用
    parent::__construct()。如果子類沒有定義構造函數則會如同一個普通的類方法一樣從父類繼承(假如沒有被定義爲
    private 的話)。
說 明:上面的類分別在 語句①和語句②使用了this指針,其實this是在實例化的時候來確定指向誰,第一次
實例化對象的時候(語句③),那麼當時this就是指向$obj1對象,那麼執行語句②的打印時就把 print( $this
->name ),那麼當然就輸出了"PBPHome"。this就是指向當前對象實例的指針,不指向任何其他對象或類。
 <二>self例
self是指向類本身,也就是self是不指向任何已經實例化的對象,一般self使用來指向類中的靜態變量假如
我們使用類裏面靜態 (一般用關鍵字static)的成員,我們也必須使用self來調用。還要注意使用self來調用
靜態變量必須使用 :: (域運算符號),見實例。
class counter  
     { 
         //定義屬性,包括一個靜態變量$firstCount,並賦初值0 語句①  
         private static $firstCount = 0; 
         private $lastCount; 
         function __construct() 
         { 
              $this->lastCount = ++self::$firstCount;//使用self來調用靜態變量 語句② 
         } 
         function printLastCount() 
         { 
              print( $this->lastCount ); 
         } 
     } 
  $obj = new Counter(); 
  $obj->printLastCount(); //執行到這裏的時候,程序輸出 1 
這 裏要注意兩個地方語句①和語句②。我們在語句①定義了一個靜態變量$firstCount,那麼在語句②的時候
使用了self調用這個值,那麼這時候我們 調用的就是類自己定義的靜態變量$frestCount。
 <二>Parent例
一般我們使用parent來調用父類的構造函數。
class Animal 
{ 
     public $name; //基類的屬性,名字$name 
     //基類的構造函數,初始化賦值 
     public function __construct( $name ) 
     { 
          $this->name = $name; 
     } 
} 
//定義派生類Person  繼承自Animal類 
class Person extends Animal 
{ 
     public $personSex;  //對於派生類,新定義了屬性$personSex性別、$personAge年齡 
     public $personAge; 
     //派生類的構造函數 
     function __construct( $personSex, $personAge ) 
     { 
          parent::__construct( "PBPHome" );     //使用parent調用了父類的構造函數 語句① 
          $this->personSex = $personSex; 
          $this->personAge = $personAge; 
     } 
     function printPerson() 
     { 
          print( $this->name. " is " .$this->personSex. ",age is " .$this->personAge ); 
      } 
} 
//實例化Person對象 
$personObject = new Person( "male", "21"); 
//執行打印 
$personObject->printPerson(); //輸出結果:PBPHome is male,age is 21 
?> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章