Problems with PHP class inheritance

Source: Internet
Author: User
class A{    public function run()    {        $this->say();    }}class B extends A{    protected function say()    {        echo 'B-say';    }}$b = new B();$b->run();//结果 输出B-say

If you change say to private, you can't.

Error PHP Fatal Error:call to Private Method B::say () from context ' A '

A private method that means that a cannot access B. Then why protected, protected should not also not be able to do? A is the parent of B is not a subclass.

Reply content:

class A{    public function run()    {        $this->say();    }}class B extends A{    protected function say()    {        echo 'B-say';    }}$b = new B();$b->run();//结果 输出B-say

If you change say to private, you can't.

Error PHP Fatal Error:call to Private Method B::say () from context ' A '

A private method that means that a cannot access B. Then why protected, protected should not also not be able to do? A is the parent of B is not a subclass.

Find out where the problem lies. The parent class can access the subclass protected protected method

This represents the object itself. Because b inherits A, B also has all the methods and properties of a. The code doesn't turn out like this.

class B extends A{    protected function say()    {        echo 'B-say';    }        public function run()    {        $this->say();    }}

The result of such execution is certainly b-say;
If the modifier of the Say method is private, it is not possible to call the say method externally, so it will be an error.

Access modifiers

Private can only be accessed in this class and is not accessible between inheriting classes
Protected inheritable classes are accessible between classes and are not accessible outside the class

That's the difference between private and protect.

Think it is very interesting, analyzed a bit, look here:
Http://www.chengxiaobai.cn/PHP/the-parent-class-calls-the-sub-class-method-in-php.html

  • 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.