欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP关键字this指向当前对象指针

程序员文章站 2022-06-03 15:45:50
...
  1. ?php
  2. class UserName
  3. {
  4. //定义属性
  5. private $name;
  6. //定义构造函数
  7. function __construct( $name )
  8. {
  9. $this->name = $name;
    //这里已经使用了this指针
  10. }
  11. //析构函数
  12. function __destruct(){}
  13. //打印用户名成员函数
  14. function printName()
  15. {
  16. print( $this->name );
    //又使用了PHP关键字this指针
  17. }
  18. }
  19. //实例化对象
  20. $nameObject = new UserName
    ( "heiyeluren" );
  21. //执行打印
  22. $nameObject->printName();
    //输出: heiyeluren
  23. //第二次实例化对象
  24. $nameObject2 = new UserName( "PHP5" );
  25. //执行打印
  26. $nameObject2->printName(); //输出:PHP5
  27. ?>

我 们看,上面的类分别在11行和20行使用了this指针,那么当时this是指向谁呢?其实this是在实例化的时候来确定指向谁,比如第一次实例化对象 的时候(25行),那么当时this就是指向$nameObject对象,那么执行18行的打印的时候就把print( $this->name ),那么当然就输出了"heiyeluren"。

第二个实例的时候,print( $this->name )变成了print( $nameObject2->name ),于是就输出了"PHP5"。所以说,PHP关键字this就是指向当前对象实例的指针,不指向任何其他对象或类。