Skip to content
Advertisement

Make abstract class method only publicly accessible from child classes

First off, we’re talking about PHP 7.4.10, but any general intel is appreaciated!

Summarized question: I’d like to define a static method in an abstract class in such a way, that the method can only be called publicly from child classes extending the abstract class but not from the abstract class itself. Sorry if I’m being too basic here, but I literally have been searching for hours for an answer and can’t even find any discussions on the topic.

Let’s consider the following example (exaplantion in the comments). I want to be able to call Apple::printName() and Pear::printName() but not Fruit::printName().

JavaScript

I’m also open for any alternative approaches as to how one might achieve the desired behaviour.

Advertisement

Answer

You can check if your instance is a subclass or not and then bail if it isnt

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement