I wrote a code segment. I don't know how to understand the inheritance of object-oriented objects. This post was last edited by the class & nbsp; ParentClass & nbsp; {& nbsp; private & nbsp; $ private & nbsp; 1; & nbsp; the code segment has been written, I don't know how to understand object-oriented inheritance.
This post was last edited by chaoxi1991 at 16:36:27, January 18 ,.
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?
PHP object-oriented inheritance
Share:
------ 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.
------ Solution --------------------
GetPrivate is the method of the ParentClass class. of course, you can use ParentClass: getPrivate to print the private attribute of ParentClass.
------ Solution --------------------
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;