我不知道这是否可能,所以我会尽力解释。
我希望有一个父类,可以通过"插件"子类轻松扩展,这些子类可能存在也可能不存在。
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初始化class Bar,b/c来自class Foo,我不知道有什么子类可用。。理想情况下,我希望它能按比例缩放,这样就无关紧要了。我希望子类在调用新Foo时自动初始化。
这可能吗。。。有没有更好的方法可以让我使用子类来修改父类的每个实例中的变量??我在WordPress中工作,所以我想我可以给Foo类一个任何子类都可以挂钩的动作挂钩,但我想知道是否有一种自然的PHP方法可以实现这一点。
我认为,根据您提供的信息,如果您真的不能以任何方式编辑Foo
的实现,那么您就太倒霉了。
继承不适用于您,因为这需要Bar
作为实例化类,而不是Foo
。当其他代码将生成Foo
类型的新对象时,您不能用Bar
悄悄地篡夺Foo
的功能。
考虑到您提到它与Wordpress相关,您可以随时要求插件开发人员向他们的init
进程添加挂钩,以允许您扩展功能。这基本上就是Wordpress允许他们的代码被第三方代码扩展的方式。
您可以像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
希望它能有所帮助,问候