Access child methods from an abstract parent class in PHP

I am working on a very simple template engine that will allow others to extend the functionality of parsing templates by subclassing the TemplateParser class. The skeleton of my TemplateParser class is as follows:

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 take a child class and add any number of replace_XXXXX methods in the child class that the parent knows about automatically. My problem is that the constant is __CLASS__always equal to "TemplateParser", even if called in a child class. Is there a way I can get child class methods from TemplateParser?

+3
source share
3 answers

static, ?

-, - COP ( ). , TemplateParser::parse_template . , (: )? , PHP 5.3 , , - . static .

-, . . :

interface ParserInterface
{
    public function parse_template($template_file);
}

interface ReplacerInterface
{
    // fill in your own interface requirements here
}

class Parser implements ParserInterface
{
    private $replacer;

    public function __construct(ReplacerInterface $replacer)
    {
        $this->replacer = $replacer;
    }

    public function parse_template($template_file)
    {
        $specials = array_filter(function($method) {
            return strpos($method, "replace_") === 0;
        }, get_class_methods($this->replacer));

        foreach ($specials as $method) {
            $this->replacer->$method($template_file);
        }
    }
}

Injection Dependency wiki, , , - static.

+4

, php 5.3 : get_called_class() / forward_static_call(). http://php.net/manual/en/language.oop5.late-static-bindings.php

:

class parent_class {
    public function method() {
        echo get_called_class(),PHP_EOL;
    }
    public static function smethod() {
        echo get_called_class(), PHP_EOL;
    }
}

class child_class extends parent_class {
}

$a = new child_class();
$a->method();
$a::smethod();

: child_class child_class

, , get_class_methods().

+1

:

// Array to hold special functions
$specials = array();

// Get all defined classes in script
$all_classes = get_declared_classes();    

// Loop through all classes
foreach($all_classes as $class)
{
   // Check if class is a child of TemplateParser
   if( is_subclass_of($class,'TemplateParser') )
   {
      // This class is a child of TemplateParser.
      // Get it methods. 
      foreach (get_class_methods($class) as $method) 
      {
         if(strpos($method, "replace_") !== false) {
            $specials[] = $method;
         }
      }
   }
}

( PHP), . , , .

0

All Articles