Detailed PHP Magic Method __get () and __set () use introduction _php tips

Source: Internet
Author: User
First look at the explanation of the official PHP documentation:
__set () is run when writing the data to inaccessible properties.
__get () is utilized to reading data from inaccessible properties.

How do you translate it in Chinese?
Inaccessible:n. It is difficult to reach, to be near, to understand.

There is code that has the truth:
Copy Code code as follows:

<?php
Error_reporting (E_all);
Class stu{
Private $a;
Private $b = 0;
Public $c;
Public $d = 0;
The private here can be replaced with protected public.
Private Function __get ($name) {
return 123;
}

Private here can also be replaced with protected public.
Private Function __set ($name, $value) {
echo "This is set function";
}
}
$s = new Stu ();
Var_dump ($s->a); Output:123
Var_dump ($s->b); Output:123
Var_dump ($s->c); Output:null
Var_dump ($s->d); output:0
Var_dump ($s->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, executing var_dump ($s->a) var_dump ($s->b) can have fatal errors
If there is no __get method, execution Var_dump ($s->e) will have a notice, prompting that no attributes are defined $e

Summary:
1. The __get () method is invoked when reading data from an inaccessible property
2. __set () method is invoked when assigning values to a property that is difficult to access
3. Inaccessible Access includes: (1) private properties, (2) Properties not initialized
4. __isset () __unset () is similar

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.