__get() - __get() will be called when reading the value of an inaccessible property.
__set() - __set() will be called when assigning a value to an inaccessible property.
/**
* Clear understanding of __get() __set()
*/
class Example {
//Public attributes
Public $public = 'pub' ;
//Protected - this attribute is available in subclasses
protected $protected = 'pro';
//Private - this attribute can only be used by this class
private $private = 'pri';
//Automatically load the __get() method 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 attribute of an object, if the attribute does not exist or is a non-public attribute, the __set() method is automatically loaded
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'; //This assignment is successful and nothing is displayed
$example->protected = 'tec';
$example->private = 'vat';
$example->other = 'er';
echo '
';
echo 'Print public attributes:'.$example->public;
The results are as follows:
name: protected, value: tec
name: private, value: vat
name:other,value:er
Print public attribute: lic