Hoping someone can help me.
I want a 'base/parent' class that holds the common functionality between two child classes, but I also want the constructor of the base/parent to decide which child class to use - so I can simply create an instance of ParentClass, and use ParentClass->method(); but what it is actually doing is deciding which child to use and creating an instance of that child.
I thought the way to do this would be to return new ChildClass(); in the constructor, but then get_class() returns the ParentClass in the 'base/shared' methods.
A little example (My class is more complex than this, so it may look odd that I for example am not just calling the child class directly):
class ParentClass {
private $aVariable;
public function __construct( $aVariable ) {
$this->aVariable = $aVariable;
if ($this->aVariable == 'a') {
return new ChildClassA();
else {
return new ChildClassB();
}
}
public function sharedMethod() {
echo $this->childClassVariable;
}
}
class ChildClassA extends ParentClass {
protected $childClassVariable;
function __construct() {
$this->childClassVariable = 'Test';
}
}
class ChildClassB extends ParentClass {
protected $childClassVariable;
function __construct() {
$this->childClassVariable = 'Test2';
}
}
I want to:
$ParentClass = new ParentClass('a');
echo $ParentClass->sharedMethod();
And expect the output to be 'Test'.
It also also my intention that a child class would have their own methods and I can use $ParentClass->nonShareMethod() to call them. So ParentClass is both acting as a 'proxy' and as a 'base'.
You cannot execute the methods of the child
class from the parent
class !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With