name = $name; //这里已经使用了this指针语句① } //析构函数
function __destruct(){} //打印用户名成员函数
function printname() { print( $this->name ); //再次使用了this指针语句②,也可以使用echo输出 }}$obj1 = new name( pbphome ); //实例化对象 语句③//执行打印
$obj1->printname(); //输出: pbphomeecho
; //输出:回车//第二次实例化对象
$obj2 = new name( php );//执行打印
$obj2->printname(); //输出:php?>
复制代码
说明:在语句①和语句②使用了this指针,那么当时this是指向谁呢?其实this是在实例化时来确定指向谁,比如第一次实例化对象的时候(语句③),那么当时this就是指向$obj1对象,那么执行语句②的打印时就把 print( $this->name ),那么当然就输出了pbphome。第二个实例的时候,print( $this->name )变成了print( $obj2->name ),于是就输出了php。所以说,this就是指向当前对象实例的指针,不指向任何其他对象或类。
再来看下self的用法。
self是指向类本身,也就是self是不指向任何已经实例化的对象,一般self使用来指向类中的静态变量。假如使用类里面静态(一般用关键字static)的成员,必须使用self来调用。注意,使用self来调用静态变量必须使用 :: (域运算符号),见实例。
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来调用父类的构造函数。
例子:
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?>
复制代码
里面同样含有this的用法。细节:成员属性都是public(公有属性和方法,类内部和外部的代码均可访问)的,特别是父类的,这是为了供继承类通过this来访问。关键点在语句①: parent::__construct( heiyeluren ),这时使用parent来调用父类的构造函数进行对父类的初始化,这样,继承类的对象就都给赋值了name为pbphome。我们可以测试下,再实例化一个对象$personobject1,执行打印后name仍然是pbphome。
总结:this是指向对象实例的一个指针,在实例化的时确定指向;self是对类本身的一个引用,一般用来指向类中的静态变量;parent是对父类的引用,一般使用parent来调用父类的构造函数。
有了以上的理论与实例相结合的介绍,你是不是已经对这三个关键词this,self,parent的理解,已经很深入了。程序员之家,祝大家学习进步。