This article describes how to use PHP magic methods _ GET and _ SET. This article provides detailed comments in the code. For more information, see _ get () -when you read the value of an inaccessible attribute, __get () will be called.
_ Set ()-When assigning values to inaccessible properties, __set () will be called.
The code is as follows:
<? Php
/**
* Clear understanding of _ get () _ set ()
*/
Class Example {
// Public attributes
Public $ public = 'pub ';
// Protected-this attribute is available in the subclass.
Protected $ protected = 'pro ';
// Private-this attribute can only be used for this type
Private $ private = 'pri ';
// The _ get () method is automatically loaded when the attribute in the access object does not exist or is not a public attribute.
Public function _ get ($ name ){
Return 'Call _ get () method: '. $ name;
}
// When assigning a value to an object attribute, the _ set () method is automatically loaded if the attribute does not exist or is not a public attribute.
Public function _ set ($ name, $ value ){
Echo "\ nname:". $ name. ', value:'. $ value. "\ n ";
}
}
$ Example = new Example;
Echo'
';
Echo $ example-> public. "\ n ";
Echo $ example-> protected. "\ n ";
Echo $ example-> private. "\ n ";
Echo $ example-> other. "\ n ";
Echo '';
$ Example-> public = 'lic '; // The value is successfully assigned and all objects are not displayed.
$ Example-> protected = 'tec ';
$ Example-> private = 'vat ';
$ Example-> other = 'ER ';
Echo'
';
Echo 'print public attributes: '. $ example-> public;
The result is as follows:
The code is as follows:
Pub
Call the _ get () method: protected
Call the _ get () method: private
Call the _ get () method: other
Name: protected, value: tec
Name: private, value: vat
Name: other, value: er
Print public property: lic