gpt4 book ai didi

php - 从 PHP 中的抽象父类访问子方法

转载 作者:可可西里 更新时间:2023-11-01 00:49:33 25 4
gpt4 key购买 nike

我正在开发一个非常简单的模板引擎,它允许其他人通过子类化 TemplateParser 类来扩展模板解析功能。我的 TemplateParser 类的框架如下所示:

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;
}
}
}

}

我想做的是能够采用子类并在父类“自动”知道的子类中添加任意数量的 replace_XXXXX 方法。我的问题是 __CLASS__ 常量始终等于“TemplateParser”,即使在子类上调用时也是如此。有什么方法可以从 TemplateParser 中获取 child 类的方法?

最佳答案

如果您要使用static 方法,为什么还要费心要求用户扩展父类?

OOP 与 COP

首先,您的建议不是OOP,而是COP(面向类的编程)。我建议您首先考虑为什么TemplateParser::parse_template 设为静态。是否有一个非常非常好的理由(提示:不太可能)?仅仅因为 PHP 5.3 引入了后期静态绑定(bind)并不意味着您应该到处使用它。事实上,static is rarely the best option .

组合优于继承

其次,您陈述的用例没有提供任何令人信服的使用继承的理由。您应该几乎总是喜欢组合而不是继承。考虑:

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);
}
}
}

在上面的代码中,我们能够获得 Dependency Injectionwiki 的所有优点与使用 static 的复杂的面向类的实现相比,我们的代码更易于测试、更易于维护并且更不容易损坏。

关于php - 从 PHP 中的抽象父类访问子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com