简体   繁体   中英

Method visibility when extending an abstract class in PHP

In my abstract class My_Class , I have a method My_Class::foo() that's called from within another method belonging to the class. For example:

abstract class My_Class {
    function foo() {
        // Stuff.
    }

    function bar() {
        $this->foo();
    }

    // More methods etc...
}

Now, I'm in the process of extending my abstract class. For example:

class My_Class_Extended extends My_Class {

}

As you'll know, both My_Class::foo() and My_Class::bar() are inherited by My_Class_Extended .

I never want My_Class::foo() to be called outside of My_Class or My_Class_Extended so I know not to make its visibility public . My problem is, I'm unsure whether to make its visibility protected or private .

My question

Considering how I'm calling My_Class::foo() in the above scenario, should it be made protected or private ? I'm not sure if the call to My_Class::foo() is coming from the child or parent class.

Thanks in advance.

One-line: protected, because you want your child classes have access


The visibility modifiers work like this:

  • public: visible from everywhere.
    • $c = new My_Class_Extended(); $c->thisIsPublic(); . This doesn't work with private or protected
  • protected: visible inside of the class and it's child classes
    • You can only call these functions inside of a function belonging to a class that derives from your parent class, or the parent class itself.
  • private: Only visible for the class it's defined in. You cannot call private functions in child classes, nor outside of the class.

The modifiers are ordered inclusively. So a protected is more restrictive than public, and private is more restrictive than protected.

You want protected, because you want to call them inside a child class, but not outside of it.


By the way: In your context, the abstract keyword only ensures that you cannot create an instance from My_Class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM