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

本文详细解析了PHP面向对象编程中this、self和parent三个关键字的使用方法及注意事项。介绍了this用于访问对象实例的属性和方法,self用于访问类的静态成员,而parent则用于从子类中调用父类的方法。

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来调用父类的构造函数和方法,也是通过域运算符::调用,不能调用属性.

转载于:https://www.cnblogs.com/gesenkof99/archive/2009/06/17/1504991.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值