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?
- <?php
- class Person
- {
- private $name;
- private $age;
- Public function __get ($property _name)
- {
- echo "Automatically calls the __get () method to get the property value <br>";
- if (isset ($this-$property _name))
- {
- return ($this,$property _name);
- }
- Else
- {
- return (NULL);
- }
- }
- Public function __set ($property _name,$value)
- {
- echo "Automatically calls the __set () method to set the property value <br>";
- $this$property _name=$value;
- }
- }
- $p 1 = new person;
- $p 1->name = "Zhang San";
- $p 1->age = 10;
- echo "name:". $p 1->name. "<br>";
- echo "Age:". $p 1->age. "<br>";
- ?>
Operation Result:
The __get () and __set () methods in PHP get set private properties