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 
?> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值