Tutorial for using __get () and __set () methods in PHP class objects

Source: Internet
Author: User
Q 1:

Class test{

Private $AA = 1;

function __get ($proName) {return $this->proname;}

}

Class Subtest extends test{

Private $AA = 2;

}

$test =new subtest ();

Echo $test->aa;

For explanation, why output 1?

A: When attempting to access a private property from outside the class, the __get method is called, if it exists, subtest inherits the test class and tries to overload AA, but there is no __get () method that accesses its private property after instantiating the Subtest class, because of the __get () method, So the default is to call the __get method of the parent class, which is also the AA property of the parent class, if you want to output 2 you can add __get () to the Subtest class

Inquiry: The method that inherits the parent class can access the child class's member property

Class test{

protected $AA = 1; function __get ($proName) {return $this, $proName;}

}

Class Subtest extends test{

protected $AA = 2;

}

$test =new subtest ();

Echo $test->aa;

A: Here output 2, because the subclass overrides the attribute AA inherited from the parent class, because they are all protected, so they can overwrite

Ask:

Class test{

Private $AA = 1;

function __get ($proName) {

return $this $proName;

}

Class Subtest extends test{

protected $AA = 2;

}

$test =new subtest ();

Echo $test->aa;

A: This time output 1, because the subclass does not overwrite the parent class's properties and does not have its own __get method, when accessing the same property, PHP by default recognizes it as private, that is, the access qualifier of the parent class is the standard, the __get () method is called when the private is recognized. So output 1

The corresponding __set () is the value of the Set property, similar in principle.

  • Related Article

    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.