Home >Backend Development >PHP Problem >How to modify private in php
How to modify the private value in php: first open the corresponding PHP code file; then use the "__get()" and "__set()" functions in PHP to assign and obtain values for private member variables.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
How to modify and obtain private variables in PHP Value
Sometimes for safety, we need to define the attributes of a class as private. However, sometimes we need to operate these private member variables. If accessed directly, an error will be reported. Therefore, in PHP5, two functions "__get()" and "__set()" are predefined to provide private member variables. Assigning and getting values, as well as "__isset()" to check attributes and "__unset()" to delete attributes.
In PHP5, we are provided with special methods to set and obtain values for private member variables, "__set()" and "__get()". These two methods do not exist by default. , but we add it to the class manually, like the constructor method (__construct()), it will only exist if it is added to the class. You can add these two methods in the following way, and of course you can also add them according to your personal style. Add:
//__get() 方法用来获取私有属性 private function __get( $ property_name ) { if ( isset ( $ this -> $ property_name )) { return ( $ this -> $ property_name ); } else { return ( NULL ); } } //__set() 方法用来设置私有属性 private function __set( $ property_name , $ value ) { $ this -> $ property_name = $ value ; }
With these two methods, you can directly execute:
echo $instance->$property 或 $instance->$property = “a”;
to obtain and modify the value of the private variable. If you do not manually add __get(); and _ The _set(); method will report an error,
because what we want to access is a private variable.
[Recommended learning: PHP video tutorial]
The above is the detailed content of How to modify private in php. For more information, please follow other related articles on the PHP Chinese website!