Describes how to use php magic methods _ get () and _ set ()

Source: Internet
Author: User
Php magic methods _ get () and _ set () are introduced. if you need them, refer to the instructions in the official php documentation:
_ Set () is run when writing data to inaccessible properties.
_ Get () is utilized for reading data from inaccessible properties.

How can I translate data in Chinese?
Inaccessible: n. hard to achieve; hard to close; ununderstandable.

Code has the truth:

The code is as follows:


Error_reporting (E_ALL );
Class stu {
Private $;
Private $ B = 0;
Public $ c;
Public $ d = 0;
// Private can be replaced by protected public.
Private function _ get ($ name ){
Return 123;
}

// Private can also be replaced by 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
?>



Result analysis:
If the _ get method is not available, executing var_dump ($ s-> a) var_dump ($ s-> B) will cause a fatal error.
If the _ get method is not available, a notice will be generated when var_dump ($ s-> e) is executed, prompting that no attribute is defined. $ e

Summary:
1. when reading data from an inaccessible attribute, the _ get () method is called.
2. when assigning values to an inaccessible attribute, the _ set () method is called.
3. difficult to access include: (1) private attributes; (2) uninitialized attributes
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.