PHP Magic Method __get () and __set () understanding

Source: Internet
Author: User

The __get () method, which is explained in the official manual, is called when a class property or method that is not defined or is not visible in the current environment is invoked (by adding: or Setting | assignment). these undefined or invisible class properties or methods are addressed by using the inaccessible properties and the inaccessible methods (inaccessible methods) later in this section. ' Undefined ' is easy to understand. We know that class permission control has three keywords ' public ', ' private ', ' protected ', which are not visible except ' public ' for __get () and __set () methods, when access and settings are undefined and defined but the keyword is ' Private,protected ' property automatically calls the __get (), __set () method.

Normally __get () returns the value of the second argument value by default, and __set () returns the value of the first parameter name by default (note: There is a bit of ambiguity here, which says that PHP ignores the return value of __set (), which means that the __set () is ignored. The custom return value in the method body returns the default return value as usual, that is, the __set () method returns the default return value anyway, and __get () does not ignore any return value, and when the method body has a return value returned, no return value returns the default return value.

And the point of note is:

Because of how PHP handles assignment operations,the return value of __set () is ignored . Similarly, in the chain assignment below, __get () is not called :

$a = $obj->b = 8; ( this notation __get () will not be called, although it seems to access a non-existent property B, assigning a property to a variable is also a condition of accessing an attribute )

PHP Magic Method __get () and __set () understanding

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.