Reputation: 6252
I have a front controller that is instantiated as follows:
$request = new FrontController();
$request->route();
The route()
method then dynamically calls the appropriate controller as needed based on the request.
Now (I think) I want all of my controllers to extend the FrontController so that they can all have access to a shared set of methods and properties, but I don't want them to inherit the route()
method as that could potentially lead to an infinite loop. If the route()
method is marked as private, however, then I can't instantiate the object as demonstrated above.
The only solution I've found is to call self::route()
from the FrontController's constructor, and then to define a blank constructor in each child controller. That just feels sloppy.
Is there a way to exclude certain methods from inheritance without marking them as private? Or should I be looking at the problem from another angle?
Upvotes: 0
Views: 168
Reputation: 2454
Are you asking whether you can selectively "turn off" inherited items? The answer to this is "no" I'm afraid, and this is basically by definition.
Two alternatives:
in a child class, where you don't want to implement such-and-such a method (/property), you can override it and return some kind of "not implemented" result.
create a series of base classes in a hierarchy, if you can, each building on the last. Then your child classes can inherit from one of the base classes, but you don't necessarily have all children inheriting from the same base class.
imo both of these approaches are pretty ugly. When I was young(er) I used to agrue about which of these was preferable, but I've long since given up doing so because its basically a six and two threes. I think if anything it depends on what the norms are in the actual environment you're writing for.
But presumably if you sit and think about it you can see why inheritance gets implemented this way.
Upvotes: 1
Reputation: 9212
You can prepend the final
modifier to a method to prevent it from being overridden by subclassing.
class FrontController{
final public function route() {
// ...
}
}
See the following PHP manual entry for more examples and a detailed explanation:
http://php.net/manual/en/language.oop5.final.php
Upvotes: 2
Reputation: 24551
Or should I be looking at the problem from another angle?
Most probably, yes. First you should think about what exactly you are trying to solve because I don't even see a real problem there. From what you've written there is no risk of an infinit loop.
Upvotes: 1