The __get () and __set () methods in PHP get set private properties

Source: Internet
Author: User
Tags vars

In a class's encapsulation, getting properties can customize the GetXXX () and Setxxx () methods, which is cumbersome when there are multiple properties in a class. The __get () and __set () methods are predefined for this PHP5, where the __get () method is used to get the value of the private member property, and the __set () method is used to assign a value to the private member property value, both of which are automatically called when the private property value is obtained or set. A case is followed to illustrate the use of these two methods.

[PHP]View Plaincopy print?
  1. <?php
  2. class Person
  3. {
  4. private $name;
  5. private $age;
  6. Public function __get ($property _name)
  7. {
  8. echo "Automatically calls the __get () method to get the property value <br>";
  9. if (isset ($this-$property _name))
  10. {
  11. return ($this,$property _name);
  12. }
  13. Else
  14. {
  15. return (NULL);
  16. }
  17. }
  18. Public function __set ($property _name,$value)
  19. {
  20. echo "Automatically calls the __set () method to set the property value <br>";
  21. $this$property _name=$value;
  22. }
  23. }
  24. $p 1 = new person;
  25. $p 1->name = "Zhang San";
  26. $p 1->age = 10;
  27. echo "name:". $p 1->name.  "<br>";
  28. echo "Age:". $p 1->age.  "<br>";
  29. ?>


Operation Result:

The __get () and __set () methods in PHP get set private properties

Related Article

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.