self parent this 区别

来源:互联网 发布:端口定义 编辑:程序博客网 时间:2024/05/16 09:33
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
原创粉丝点击