Write a piece of code, do not know how to understand the object-oriented inheritance

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