PHP类中的$this、self、parent关键字使用总结

$this

$this是指向对象实例的一个指针(在实例化的时候来确定指向),不指向任何其他对象或类

使用形式:$this->实例属性或实例方法()

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

  

self关键字

self是指向类本身,也就是self是不指向任何已经实例化的对象,一般self使用来指向类中的静态变量。假如我们使用类里面静态(一般用关键字static)的成员,我们也必须使用self来调用。

注意其中使用self来调用静态变量必须使用:: (域运算符号),使用形式:self :: 静态属性或静态方法();

 class counter     //定义一个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

这里要注意两个地方语句①和语句②。我们在语句①定义了一个静态变量$firstCount,那么在语句②的时候使用了self调用这个值,那么这时候我们调用的就是类自己定义的静态变量$frestCount。我们的静态变量与下面对象的实例无关,它只是跟类有关,那么我调用类本身的的,那么我们就无法使用this来引用,因为self是指向类本身,与任何对象实例无关。然后前面使用的this调用的是实例化的对象$obj,大家不要混淆了。

parent

parent是指向父类的指针,一般我们使用parent来调用父类的构造函数。实例如下:

//建立基类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

成员属性都是public(公有属性和方法,类内部和外部的代码均可访问)的,特别是父类的,这是为了供继承类通过this来访问。关键点在语句①:parent::__construct( "heiyeluren"),这时候我们就使用parent来调用父类的构造函数进行对父类的初始化,这样,继承类的对象就都给赋值了name为PBPHome