PHP magic method _ GET, _ SET use instance

Source: Internet
Author: User
This article describes how to use PHP magic methods _ GET and _ SET. This article provides detailed comments in the Code. For more information, see

This article describes how to use PHP magic methods _ GET and _ SET. This article provides detailed comments in the Code. For more information, see

_ Get ()-when the value of the inaccessible attribute is read, __get () will be called.

_ Set ()-When assigning values to inaccessible properties, __set () will be called.

The Code is as follows:


<? Php

/**
* Clear understanding of _ get () _ set ()
*/
Class Example {

// Public attributes
Public $ public = 'pub ';
// Protected-this attribute is available in the subclass.
Protected $ protected = 'pro ';
// Private-this attribute can only be used for this type
Private $ private = 'pri ';

// The _ get () method is automatically loaded when the attribute in the access object does not exist or is not a public attribute.
Public function _ get ($ name ){
Return 'call _ get () method: '. $ name;
}

// When assigning a value to an object attribute, the _ set () method is automatically loaded if the attribute does not exist or is not a public attribute.
Public function _ set ($ name, $ value ){
Echo "\ nname:". $ name. ', value:'. $ value. "\ n ";
}
}

$ Example = new Example;
Echo'

';
Echo $ example-> public. "\ n ";
Echo $ example-> protected. "\ n ";
Echo $ example-> private. "\ n ";
Echo $ example-> other. "\ n ";
Echo '';
$ Example-> public = 'lic '; // The value is successfully assigned and all objects are not displayed.
$ Example-> protected = 'tec ';
$ Example-> private = 'vat ';
$ Example-> other = 'er ';
Echo'
';
Echo 'print public attributes: '. $ example-> public;

The result is as follows:

The Code is as follows:


Pub
Call the _ get () method: protected
Call the _ get () method: private
Call the _ 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.