self parent this区別

2789 ワード

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 
?>