PHP inheritance: I wrote a code to test the inheritance relationship. the code is as follows: & lt; html & gt; & lt; body & gt; & lt ;? Phpclass & nbsp; A {public & nbsp; $ pub_A; private & nbsp; $ pri_A; public & nbsp; function & nbsp; pub () {$ this-& gt; small issues with PHP inheritance
I wrote a code to test the inheritance relationship, as follows:
Class
{
Public $ pub_A;
Private $ pri_A;
Public function pub ()
{
$ This-> pub_A = 'it is public of! ';
Echo"
". $ This-> pub_A ."
";
}
Protected function pri ()
{
$ This-> pri_A = 'it is private of! ';
Echo"
". $ This-> pri_A ."
";
}
}
Class B extends
{
Public $ pub_ B;
Private $ pri_ B;
Function _ construct ()
{
Echo"
". $ This-> pri ()."
";
$ This-> pri_A = 10;
Echo"
". $ This-> pri_A ."
";
}
}
$ B = new B;
?>
I marked it out. in parent class A, $ pri_A is private and cannot be inherited by quilt class B. Why can I assign values to pri_A and display the number after the assignment?
------ Solution --------------------
Private: methods or attributes can only be accessed from one member of the class, and cannot be accessed from members of the inherited class.
Methods or attributes marked with the private tab can be redefined in the inheritance class.
Each class can only see its own private method.
------ Solution --------------------
Subclass can access attributes of the parent class through the public method of the parent class
------ Solution --------------------
I tested the code. if $ pri_A = "aaa" is assigned in A, the value cannot be obtained without assigning A value in B. After assigning A value in B, the value is obtained, it can be seen that the private attributes of the parent class can be redefined in the subclass.
------ Solution --------------------
Reference
I marked it out. in parent class A, $ pri_A is private and cannot be inherited by quilt class B. Why can I assign values to pri_A and display the number after the assignment?
The problem is that the subclass accesses the private member of the parent class.
Instead, the subclass calls the $ this-> pri () method.
This method inherits the parent class
However, this method of the parent class calls the private member of the parent class.
------ Solution --------------------
Yes, private attributes are not inherited!
You can see this
Function _ construct ()
{
Echo"
". $ This-> pri ()."
";
Echo isset ($ this-> pri_A )? 'Yes': 'no'; // no will be output here
$ This-> pri_A = 10;
Echo"
". $ This-> pri_A ."
";
}
The pri () method is a parent class and can naturally access its private attributes.
After you $ this-> pri_A = 10;, a public attribute (public) named pri_A will be created in object $ B)
You can see this
Print_r ($ B );
Output:
B Object
(
[Pub_ B] =>
[Pri_ B: private] =>
[Pub_A] =>
[Pri_A: private] => It is private of!
[Pri_A] => 10
)