从父类PHP自动构造子类

时间:2012-07-22 15:08:27

标签: php oop

我不知道这是否可能,所以我会尽力解释。

我希望有一个父类可以通过“插件”子类轻松扩展,这些子类可能存在也可能不存在。

class Foo {
__construct(){
   $this->foo = "this is foo";
}
}

class Bar extends Foo {
   function construct(){
    parent :: __construct;
  }
   $this->foo = "foo is now bar";
}

但我不想每次需要时用$ bar = new Bar来初始化类Bar,来自Foo类的b / c我不知道哪些子类可用..理想情况下我会喜欢它,所以它无关紧要。我希望子类在任何需要新Foo的时候自动初始化。

这是可能的...有没有更好的方法来实现它,以便我可以使用子类来修改父类的每个实例中的变量?我在WordPress中工作,所以我想我可以给Foo类一个动作钩子,任何子类都可以挂钩,但我想知道是否有一种自然的PHP方法来实现这一点。

2 个答案:

答案 0 :(得分:3)

我认为根据您提供的信息,如果您真的无法以任何方式编辑Foo的实现,那么您将非常幸运。

继承不适合您,因为这需要Bar作为实例化的类,而不是Foo。当其他代码创建Foo类型的新对象时,您无法以Bar默默使用Foo的功能。

鉴于您提到它与Wordpress相关,您可以随时要求插件开发人员为其init进程添加挂钩以允许您扩展功能。这基本上就是Wordpress如何通过第三方代码扩展其代码。

答案 1 :(得分:0)

你可以像Zend这样的框架做到这一点。

将所有子类放在文件夹中,让let say plugin文件夹,并将该文件命名为与类名相同的文件。比如把class Bar {}放在插件文件夹

中的Bar.php中 Bar.php中的

class Bar extends Foo {
   function construct(){
    parent :: __construct;
  }
   $this->foo = "foo is now bar";
}

Class Foo将是

class Foo {
__construct(){

foreach (glob("plugins/*.php") as $filename) // will get all .php files within plugin directory
  {
    include $filename;
    $temp = explode('/',$filename);
    $class_name = str_replace('.php',$temp[count($temp)-1]); // get the class name 
    $this->$class_name = new $class_name;   // initiating all plugins
  }


}
}

$foo = new Foo();
echo $foo->bar->foo;  //foo is now bar

希望它有所帮助,问候