I wrote a code segment and I don't know how to understand object-oriented inheritance.

Source: Internet
Author: User
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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.