【发布时间】:2010-09-20 23:02:13
【问题描述】:
我有一个由大约十个子类继承的基类。这些子类中的大多数具有非常相似的行为,但我只想为其中的三个定义专门的方法。
是否可以通过在每次实例化子类的对象时自动加载父类来伪装这些类的存在?这样我就不必用相同的代码定义多个类了?
例如
class ParentClass {
public function __construct() {
switch(get_class($this)) {
case "ChildClass1" : do_stuff() break;
case "ChildClass2" : do_other_stuff() break;
default: break;
}
}
}
$c1 = new ChildClass1();
$c2 = new ChildClass2();
...只有一个文件ParentClass.php(没有单独的文件ChildClass1.php 或ChildClass2.php)。
【问题讨论】:
-
不要为了节省创建几个文件而扭曲您的代码。如果您将共享实现放在
ParentClass中,并且仅在子类中必要时覆盖,则文件ChildClass1.php和ChildClass2.php将不会有重复的代码。
标签: php class inheritance autoload