Php Objects directly access private properties

Source: Internet
Author: User
Php Objects directly access private properties
 Name = $ name; $ this-> age = $ age; $ this-> sex = $ sex;}/* output Cannot access private property Person :: the $ name object cannot directly access and set the value of the private attribute, but it can be done through the magic method _ get ($ proName) and _ set ($ proName, $ proValue. step: 1. override magic method _ get ($ property), _ set ($ proName, $ proValue) 2. use an object to directly access or set a private attribute $ p1-> name = "object to directly access a private attribute"; echo $ p1-> name; 3. when an object directly accesses or sets a private attribute, the magic method _ get ($ proName) and _ set ($ proName, $ proValue) are automatically called) */function _ get ($ proName) {return $ this-> $ proName;} function _ set ($ proName, $ proValue) {$ this-> $ proName = $ proValue;} function say () {echo "$ this-> name: My age $ this-> age, gender: $ this-> sex
";}Function run () {$ this-> left (); $ this-> right ();} private function left () {echo" left ";} private function right () {echo "right";} // destructor. function _ destruct () {echo "$ this-> name: i'm leaving
";}}$ P1 = new Person (" name1 ", 15," female "); $ p2 = new Person (" name2 ", 20," male "); $ p3 = new Person ("name3", 30, "female "); /* directly access the object or set the private property */$ p1-> name = "object directly access the private property"; echo $ p1-> name."
";/* Output, note _ destruct () output order name1: my age 15, Gender: Female name2: my age 20, Gender: Male name3: my age is 30, Gender: Female name1: I 've gone name3: I 've gone name2: I 've gone */$ p1-> say (); $ p2-> say (); $ p3-> say (); $ p1 = null;?>

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.