I don’t know if this is possible so i will try to explain as best as I can.
I’d like to have a parent class that is easily extensible by “plugin” child classes that may or may not be present.
class Foo {
__construct(){
$this->foo = "this is foo";
}
}
class Bar extends Foo {
function construct(){
parent :: __construct;
}
$this->foo = "foo is now bar";
}
but I don’t want to have to initialize class Bar with $bar = new Bar every time i need it, b/c from class Foo I won’t know what child classes are available.. and ideally i’d like it to scale so it doesn’t matter. i’d like the child class to automatically initialize any time there is a call for a new Foo.
is this possible… is there a better way to go about it so that I can use the child class to modify a variable in every instance of the parent class?? i’m working within WordPress, so I think I could give class Foo an action hook that any child classes could hook into, but I am wondering if there is a natural PHP way to achieve this.
I think given the information you’ve provided, if you really can’t edit the implementation of
Fooin any way, then you’re pretty much out of luck.Inheritance won’t work for you, since that would require
Barto be the instantiated class, notFoo. You can’t silently usurpFoos functionality withBarwhen other code will be making new objects of typeFoo.Given that you mentioned it’s WordPress related, you could always ask the plugin developer to add hooks to their
initprocess to allow you to extend the functionality. This is basically how WordPress goes about allowing their code to be extended by third-party code.