现在的位置: 首页 > 综合 > 正文

PHP面向对象中this,self,parent区别和使用

2012年01月28日 ⁄ 综合 ⁄ 共 2020字 ⁄ 字号 评论关闭

this是指向对象实例的一个指针,self是对类本身的一个引用,parent是对父类的引用。

this:

<?php

 class UserName
 

     
//定义属性    
     
private $name;
 
     
//定义构造函数
     
function __construct$name )
     {
          
$this->name $name//这里已经使用了this指针
     
}
 
     
//析构函数
     
function __destruct(){}

     //打印用户名成员函数
     
function printName()
     {
          print( 
$this->name ); //又使用了this指针
     
}
 }

 //实例化对象
 
$nameObject = new UserName"heiyeluren" );

 //执行打印
 
$nameObject->printName(); //输出: heiyeluren
 
 //第二次实例化对象
 
$nameObject = new UserName"PHP" );
 
 
//执行打印
 
$nameObject->printName(); //输出:PHP
 
?> 

注意:this不能引用静态变量,this是指向当前对象.

 

self:

<?php

     class Counter
     
{
         
//定义属性,包括一个静态变量
         
private static $firstCount = ;
         private 
$lastCount;

         //构造函数
         
function __construct()
         {
              
$this->lastCount = ++selft::$firstCount//使用self来调用静态变量,使用self调用必须使用::(域运算符号)
         
}

         //打印最次数值
         
function printLastCount()
         {
              print( 
$this->lastCount );
         } 
     }

 //实例化对象
 
$countObject = new Counter();

 $countObject->printLastCount(); //输出 

 ?> 

注意:self是指向类本身,也就是self是不指向任何已经实例化的对象,一般self使用来指向类中的静态变量和静态方法。

但凡self通过域运算符::调用的静态变量或者静态方法使用的静态变量都必须经过初始化,否则会报变量未初始化.

注意调用静态变量要带$

 

parent:

 

<?php

 //基类
 
class Animal
 
{
     
//基类的属性
     
public $name//名字

     //基类的构造函数
     public function __construct$name )
     {
          
$this->name $name;
     }
 }

 //派生类
 
class Person extends Animal //Person类继承了Animal类
 
{
     public 
$personSex//性别
     
public $personAge//年龄

     //继承类的构造函数
     function __construct$personSex$personAge )
     {
          
parent::__construct"heiyeluren" ); //使用parent调用了父类的构造函数
          
$this->personSex $personSex;
          
$this->personAge $personAge;
     }

     function printPerson()
     {
          print( 
$this->name" is " .$this->personSex",this year " .$this->personAge );
      }
 }

 //实例化Person对象
 
$personObject = new Person"male""");

 //执行打印
 
$personObject->printPerson(); //输出:heiyeluren is male,this year 

 ?> 

 

我们知道parent是指向父类的指针,一般我们使用parent来调用父类的构造函数和方法,也是通过域运算符::调用,不能调用属性.

抱歉!评论已关闭.