PHP keyword this points to the current object pointer

Source: Internet
Author: User

  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 the username member function
  14. Function printName ()
  15. {
  16. Print ($ this->Name );
    // The PHP keyword this pointer is used again.
  17. }
  18. }
  19. // Instantiate the object
  20. $ NameObject = new UserName
    ("Heiyeluren ");
  21. // Execute print
  22. $ NameObject->PrintName ();
    // Output: heiyeluren
  23. // The second Object Instantiation
  24. $ NameObject2 = new UserName ("PHP5 ");
  25. // Execute print
  26. $ NameObject2->PrintName (); // output: PHP5
  27. ?> 

We can see that the class above uses the this pointer in 11 rows and 20 rows respectively. Who is this pointing? In fact, this is used to determine who to point to during instantiation. For example, when the object is first instantiated (25 rows), then this is to point to the $ nameObject object, when printing 18 rows, the print ($ this-> <name) is changed to the print ($ nameObject-> name), and the "heiyeluren" is output ".

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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.