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:
$c = new My_Class_Extended(); $c->thisIsPublic();
. This doesn't work with private or protected 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.