I wrote some code, but I don't know how to understand the inheritance of object-oriented. This post was last edited by chaoxi1991 at 16:36:27, January 18 ,.
PHP object-oriented inheritance
class ParentClass { private $private = 1; public function getPrivate() { echo 'getPrivate() belong to class "' . get_class($this) . '"
'; return $this->private; }}class Son extends ParentClass {}$son = new Son();echo 'private=' . $son->getPrivate();
I expected the result to be an error, but no error was reported.
The execution result is:
In class "ParentClass" function getPrivate (): "Son"
Private = 1
Why is the $ private property printed?
Reply to discussion (solution)
It cannot be printed in this way, and how can you expose this $ private?
Php private refers to the attribute or method, and you cannot directly access it from outside, meaning
You cannot access $ son-> private in this way, but can only be exposed through the internal public method.
GetPrivate is the method of the ParentClass class. of course, you can use ParentClass: getPrivate to print the private attribute of ParentClass.
As mentioned in the #1, #2 floor, because the subclass inherits the methods of the base class, the methods of the base class can print private attributes.
Subclass cannot inherit the private attributes of the base class.
Therefore, what I want to see is
Echo $ son-> $ private;
It cannot be printed in this way, and how can you expose this $ private?
Php private refers to the attribute or method, and you cannot directly access it from outside, meaning
You cannot access $ son-> private in this way, but can only be exposed through the internal public method.
Private needs to get its value in a non-direct way. I understand this.
What I don't understand is: why does the getPrivate () method call the get_class () function get "Son" instead of "ParentClass"
GetPrivate is the method of the ParentClass class. of course, you can use ParentClass: getPrivate to print the private attribute of ParentClass.
Since the getPrivate () method belongs to the "ParentClass" class, why does it print get_class () in the getPrivate () method, but it is "Son" instead of "ParentClass "?
The contradiction lies in the method getPrivate () in the parent class. "$ this" represents the instance of which class, parent class or subclass?
[See the following example in the description of the get_class () method.
Expected result:
string(3) "foo"string(3) "bar"
In this case, "$ this" refers to a subclass instance in the base class, and an undefined error should be reported when "$ this-> private" is executed in my example .]