I am working on a very simple template engine that would allow others to extend the template parsing functionality via subclassing the TemplateParser class. The skeleton of my TemplateParser class looks like this:
abstract class TemplateParser {
public static function parse_template($template_file) {
//Do stuff with $template_file
$specials = array();
foreach (get_class_methods(__CLASS__) as $method) {
if(strpos($method, "replace_") !== false) {
$specials[] = $method;
}
}
}
}
What I would like to do is be able to take a child class and add any number of replace_XXXXX methods in the child class that the parent “automatically” knows about. My problem is that the __CLASS__ constant is always equal to ‘TemplateParser’, even when called on a child class. Is there any way that I can get the methods of the child class from within TemplateParser?
If you’re going to use a
staticmethod why even bother asking users to extend the parent class?OOP vs. COP
First, what you’re suggesting is not OOP — it’s COP (Class Oriented Programming). I’d advise you to consider exactly why you’ve made
TemplateParser::parse_templatestatic in the first place. Is there a really, really good reason (hint: not likely)? Just because PHP 5.3 introduced late-static binding doesn’t mean you should use it willy-nilly all over the place. In fact,staticis rarely the best option.Composition Over Inheritance
Second, your stated use-case doesn’t provide any compelling reason for using inheritance. You should almost always favor composition over inheritance. Consider:
In the above code we’re able to reap all the advantages of Dependency Injectionwiki and our code is imminently more testable, maintainable and less prone to breakage than had we used a convoluted class-oriented implementation with
static.