search
Homephp教程php手册PHP关键字this指向当前对象指针

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

Jun 13, 2016 am 11:11 AM
phpprivatethisKeywordsdefinitionobjectAttributesorientedpointer

  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就是指向当前对象实例的指针,不指向任何其他对象或类。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor