Detailed PHP Magic Methods __get () and __set ()

Source: Internet
Author: User

Let's take a look at the explanations of the PHP official documentation:
__set () is the run when writing data to inaccessible properties.
__get () is utilized for reading data from inaccessible properties.

How do you translate it in Chinese?
Inaccessible:n. Hard to reach, difficult to access, incomprehensible.
There is the truth in code:

<?PHPerror_reporting(E_all);classstu{Private $a; Private $b= 0;  Public $c;  Public $d= 0; //the private here can be replaced with protected public    Private function__get ($name) {        return123; }        //The private can also be replaced with protected public    Private function__set ($name,$value) {        Echo"This is set function"; }} $s=NewStu ();Var_dump($s-&GT;A);//output:123Var_dump($s-&GT;B);//output:123Var_dump($s-&GT;C);//Output:nullVar_dump($s-&GT;D);//output:0Var_dump($s-&GT;E);//output:123 $s->a = 3;//Output:this is set function$s->c = 3;//No output$s->f = 3;//Output:this is set function?>

Results Analysis:

If there is no __get method, execution of Var_dump ($s->a) var_dump ($s->b) can have fatal errors
If there is no __get method, the execution of Var_dump ($s->e) has a notice, prompting that no attribute is defined $e

Summarize:
1. When reading data from an inaccessible property, the __get () method is called
2. When assigning values to an inaccessible property, the __set () method is called
3. Difficult to access includes: (1) Private attributes, (2) Properties without initialization
4. __isset () __unset () is similar

(Transferred from Http://www.cnblogs.com/glory-jzx/archive/2012/05/23/2514173.html)

Detailed PHP Magic Methods __get () and __set ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.