Php Magic Method __get, __set use instance _php skill

Source: Internet
Author: User

__get ()-When reading the value of an inaccessible property, __get () is invoked.

__set ()-__set () is invoked when a value is assigned to an inaccessible property.

Copy Code code as follows:

<?php

/**
 * A clear Understanding __get () __set ()
 */
class Example {
   
   / /publicly owned properties
    public $public = ' pub ';
   //protected-subclass this property is available in
    Pro tected $protected = ' Pro ';
   //private-use this property only for this class
    private $private = ' pri ';
   
&nb sp;  ///__get () method
    Public Function __get ($name) {
When accessing properties in an object that do not exist or Non-public properties         return ' calls the __get () method: '. $name;
   }
   
   //When assigning a property to an object, automatically loads the __set () method
   If the property does not exist or is not a public property.   Public Function __set ($name, $value) {
        echo \nname:. $name. ', Value: '. $value. ' \ n ";
   }
}

$example = new example;
Echo ' <pre> ';
echo $example->public. " \ n ";
echo $example->protected. " \ n ";
echo $example->private. " \ n ";
echo $example->other. " \ n ";
Echo ' $example->public = ' lic '; This assignment succeeded to all without showing
$example->protected = ' tec ';
$example->private = ' VAT ';
$example->other = ' er ';
Echo ' <br/> ';
Echo ' Prints public properties: '. $example->public;

The results are as follows:

Copy Code code as follows:

Pub
Call __get () method: protected
Call __get () method: Private
Call __get () method: Other

Name:protected,value:tec

Name:private,value:vat

Name:other,value:er

Print Public Property: Lic

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.