PHP keyword this points to the current object pointer_PHP tutorial

WBOY
Release: 2016-07-15 13:34:35
Original
928 people have browsed it

  1. < ?php
  2. class UserName
  3. {
  4. //Define attributes
  5. private $name;
  6. //Define the constructor
  7. function __construct( $name )
  8. {
  9. $this-> name = $name;
    //This pointer has been used here
  10. }
  11. //Destructor
  12. function __destruct(){}
  13. //Print username member function
  14. function printName()
  15. {
  16. print( $this- >name );
    //The PHP keyword this pointer is used again
  17. }
  18. }
  19. //Instantiated object
  20. $nameObject = new UserName
    ( "heiyeluren" );
  21. //Perform printing
  22. $nameObject->printName();
    //Output: heiyeluren
  23. //Second instantiation of the object
  24. $nameObject2 = new UserName( "PHP5" );
  25. // Execute printing
  26. $nameObject2->printName(); //Output :PHP5
  27. ?>

Let’s see, the above class uses this pointer on lines 11 and 20 respectively, so who does this point to at that time? In fact, this determines who it points to when instantiating it. For example, when the object is instantiated for the first time (line 25), then this points to the $nameObject object. Then when printing on line 18, print( $this ->name ), then of course "heiyeluren" is output.

In the second instance, print( $this->name ) becomes print( $nameObject2->name ), so "PHP5" is output. Therefore, the PHP keyword this is a pointer to the current object instance and does not point to any other object or class.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445969.htmlTechArticle?php classUserName { //Define attributes private$name; //Define constructor function__construct($name) { $ this- name =$name; //This pointer has been used here} //Destructor function_...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!