PHP关键字this指向当前对象指针
- < ?php
- class UserName
- {
- //定义属性
- private $name;
- //定义构造函数
- function __construct( $name )
- {
- $this->name = $name;
//这里已经使用了this指针 - }
- //析构函数
- function __destruct(){}
- //打印用户名成员函数
- function printName()
- {
- print( $this->name );
//又使用了PHP关键字this指针 - }
- }
- //实例化对象
- $nameObject = new UserName
( "heiyeluren" ); - //执行打印
- $nameObject->printName();
//输出: heiyeluren - //第二次实例化对象
- $nameObject2 = new UserName( "PHP5" );
- //执行打印
- $nameObject2->printName(); //输出:PHP5
- ?>
我 们看,上面的类分别在11行和20行使用了this指针,那么当时this是指向谁呢?其实this是在实例化的时候来确定指向谁,比如第一次实例化对象 的时候(25行),那么当时this就是指向$nameObject对象,那么执行18行的打印的时候就把print( $this-><name )变成了print( $nameObject->name ),那么当然就输出了"heiyeluren"。
第二个实例的时候,print( $this->name )变成了print( $nameObject2->name ),于是就输出了"PHP5"。所以说,PHP关键字this就是指向当前对象实例的指针,不指向任何其他对象或类。
永久链接:http://www.phprm.com/frame/php1004002.html
转载随意!带上文章地址吧。