Question 1: classTest {private $ aa1; function _ get ($ proName) {return $ this-& gt; proName ;}} classsubTestextendsTest {private $ aa2 ;} $ testnewsubTest (); echo $ test-& gt; aa; why is output 1? A: When attempting to access a private property from outside the class, the __get method will be called. Question 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;
Why output 1?
A: When attempting to access a private attribute from outside the class, the __get method will be called. if it exists, subTest inherits the Test class and tries to reload aa, but there is no _ get () method. when the subTest class is instantiated and its private attributes are accessed, the _ get () method calls the _ get method of the parent class by default, of course, the access is also the aa attribute of the parent class. if you want to output 2, you can add _ get () for the subTest class ()
Question: Can the method that inherits the parent class access the member attributes of the subclass?
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 overwrites the property aa inherited from the parent class, because they are all protected, so they can overwrite
Follow-up:
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 output 1 is because the subclass does not cover the attributes of the parent class and does not have its own _ get method. when accessing the same attribute, php recognizes it as private by default, this is based on the access qualifier of the parent class. after private is identified, the _ get () method is called, so 1 is output.
The corresponding _ set () is the value of the set attribute. The principle is similar.