3

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

我想要一个父类,它可以通过可能存在或不存在的“插件”子类轻松扩展。

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 方式来实现这一点。

4

2 回答 2

3

我认为鉴于您提供的信息,如果您真的无法Foo以任何方式编辑的实现,那么您非常不走运。

继承对你不起作用,因为那需要Bar是实例化的类,而不是Foo. 当其他代码将创建新的 type 对象时,您不能默默地篡夺Foos 的功能。BarFoo

鉴于您提到它与 Wordpress 相关,您总是可以要求插件开发人员在他们的init流程中添加挂钩以允许您扩展功能。这基本上就是 Wordpress 允许第三方代码扩展其代码的方式。

于 2012-07-22T15:40:36.257 回答
0

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

将所有子类放在文件夹中,比如说插件文件夹并将文件命名为与类名相同。喜欢放在class Bar {}插件文件夹中的 Bar.php

在 Bar.php 中

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

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

希望它有帮助,问候

于 2012-07-23T10:48:30.390 回答