Write a piece of code, do not know how to understand the object-oriented inheritance
This post was last edited by chaoxi1991 on 2013-10-18 16:36:27
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 there was no error.
The execution results are:
In class "ParentClass" function getprivate (): "Son"
Private=1
Want to ask why $private private properties will be printed out? PHP Object Oriented Inheritance
Share to:
------Solution--------------------
That's not going to print out, and how do you think this $private can be exposed?
PHP private refers to a property or method that you cannot directly access by external means
You cannot $son->private so to visit, but only through the internal public method exposed.
------Solution--------------------
Getprivate is a method of ParentClass class, of course, can print out the private property of ParentClass by Parentclass::getprivate
------Solution--------------------
As of # #, #2楼所说, because subclasses inherit the methods of the base class, the methods of the base class can print out private properties.
The subclass cannot inherit the private properties of the base class
So the landlord wants to see the result is actually
echo $son $private;