php中this、self、parent 的区别

参考自:http://www.cnblogs.com/myjavawork/articles/1793664.html

php5相对php4而言在面向对象方面有很多提升,成为了具有大部分面向对象语言的特性的语言。这里主要谈一下this、self、parent之间的区别。this是指向对象的指针,self是指向类本身的指针,parent是指向父类的指针。

1.关于this

<?php
 
class  name {         //建立了一个名为name的类
  
  private  $name;         //定义属性,私有
 
  //定义构造函数,用于初始化赋值
  function __construct( $name ){
         
    $this->name =$name;         //这里已经使用了this指针语句①
  
  }
 
  //析构函数  
  function __destruct(){}
 
  //打印用户名成员函数
  function printname(){
    
    print( $this->name);             //再次使用了this指针语句②,也可以使用echo输出
  }

}

$obj1 = new name("PBPHome");   //实例化对象 语句③
 
//执行打印
$obj1->printname(); //输出:PBPHome
echo"<br>";                                    //输出:回车
 
//第二次实例化对象 语句4
$obj2 = new name( "PHP" );   
 
//执行打印
$obj2->printname();                         //输出:PHP
 
?>

 说明:在语句1和语句2时分别使用了this,在执行到这两个语句事this并没有确定指向谁,只有在执行到语句3时第一次实例化对象时才确定this指向对象$obj1,然后继续向下,第二次实例化语句4时,this指向$obj2,也就是说this指向当前对象实例。


2.关于self

一般self使用来指向类中的静态变量。假如我们使用类里面静态(一般用关键字static)的成员,我们也必须使用self来调用。还要注意使用self来调用静态变量必须使用:: (域运算符号),见实例。
<?php
 
    classcounter{     //定义一个counter的类
    
        //定义属性,包括一个静态变量$firstCount,并赋初值0 语句①  
        private  static  $firstCount = 0;
        private  $lastCount;
 
        //构造函数
        function __construct(){
        
             $this->lastCount =++self::$firstCount;      //使用self来调用静态变量 语句②
        }
 
        //打印lastCount数值
        function printLastCount(){
        
             print( $this->lastCount );
        
        }
    }
 
  //实例化对象
  $obj = new Counter();
 
  $obj->printLastCount();                             //执行到这里的时候,程序输出1
 
 ?>

说明:我们在语句1时定义了静态变量$firstCount并赋值为0,语句2则用self来调用自己类中的静态变量与实例化对象无关。且静态变量只能有类名self::来调用


3.关于parent
一般使用parent调用父类中的构造函数。
<?php
 //建立基类Animal
 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;
    }
 
    //派生类的成员函数,用于打印,格式:名字 is name,age is 年龄
    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
 
 ?>


说明:语句1中parent::__construct("PBPHome"),用于父类的初始化。

总结:this是指向对象实例的一个指针,在实例化的时候确认指向;self是对类本身的一个引用,一般用来指向类中的静态变量;parent是对父类的引用,一般用来调用父类的构造函数。

原文地址:https://www.cnblogs.com/xiaoyueer/p/2976077.html