如何仅在父类定义buildTemplatePath()实现PHP类继承链路径拼接
解决方案
你可以只在抽象父类 key 中实现 buildTemplatePath() 方法,通过遍历继承链或递归调用的方式自动拼接路径,无需在每个子类重复定义。以下是两种可行的实现方式:
方式一:递归调用父类方法
利用PHP的继承特性,在抽象类中通过递归向上调用父类方法,逐步拼接路径片段:
abstract class key { public function buildTemplatePath() { // 获取当前实例的类名 $currentClass = get_class($this); // 终止条件:到达最顶层的抽象类key,返回空字符串 if ($currentClass === __CLASS__) { return ''; } // 提取类名中key_后缀的部分(比如key_main提取main) $segment = str_replace('key_', '', $currentClass); // 递归调用父类的方法获取上层路径 $parentPath = parent::buildTemplatePath(); // 拼接路径:如果父路径不为空则加斜杠分隔 return $parentPath ? "{$parentPath}/{$segment}" : $segment; } } // 子类无需再定义buildTemplatePath方法,直接继承即可 class key_main extends key {} class key_submenu extends key_main {} class key_navpoint extends key_submenu {} // 测试调用 $navpoint = new key_navpoint(); echo $navpoint->buildTemplatePath(); // 输出: main/submenu/navpoint
方式二:遍历继承链收集路径片段
通过循环遍历当前类的继承链,收集所有层级的类名片段,最后拼接成路径:
abstract class key { public function buildTemplatePath() { $segments = []; $currentClass = get_class($this); // 遍历继承链,直到到达顶层抽象类key while ($currentClass !== __CLASS__) { // 提取当前类的路径片段 $segments[] = str_replace('key_', '', $currentClass); // 获取父类类名 $currentClass = get_parent_class($currentClass); } // 反转数组(因为遍历是从子类到父类,需要调整顺序) return implode('/', array_reverse($segments)); } } // 子类定义同上,测试结果一致 $navpoint = new key_navpoint(); echo $navpoint->buildTemplatePath(); // 输出: main/submenu/navpoint
为什么之前的get_parent_class($this)尝试失败?
你之前的问题大概率是递归逻辑没有处理好终止条件,或是没有正确提取类名中的路径片段。上面两种方案都无需在子类中重复定义方法,仅通过抽象父类的逻辑即可自动适配整个继承链。
内容的提问来源于stack exchange,提问作者SQRCAT
相关产品推荐
相关产品推荐

