PHP magic methods __GET, __SET usage examples, __get__set_PHP tutorial

WBOY
Release: 2016-07-13 10:13:14
Original
1338 people have browsed it

PHP magic methods __GET, __SET usage examples, __get__set

__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.

Copy codeThe code is as follows:

/**
* 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:

Copy codeThe 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 attribute: lic

www.bkjia.com true http: //www.bkjia.com/PHPjc/917032.html TechArticle PHP magic methods __GET, __SET usage examples, __get__set __get() - when reading the value of an inaccessible attribute, __get() will be called. __set() - When assigning a value to an inaccessible property, __set() will be...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!