For some more complicated class hierarchy I was playin around with a minimal example for this problem a bit.
This class is given - the method "createOrUpdate()" may be modified:
class A {
protected $a;
protected $b;
protected $c;
function __construct($a,$b,$c) {
$this->a = $a;
$this->b = $b;
$this->c = $c;
}
public static function createOrUpdate($a,$b,$c) {
if(self::exists($b)) {
someWhateverUpdate();
} else {
new static($a,$b,$c);
}
}
}
Now lets see what happens if we extend it:
class B extends A {
function __construct($a,$b,$c) {
parent::__construct($a,$b,$c);
}
}
B::createOrUpdate("rock","this","now");
Works fine!
class C extends B {
function __construct($a,$b) {
parent::__construct($a,$b,"exactly");
}
}
C::createOrUpdate("rock","this","now");
Works also fine however if somebody does createOrUpdate() parameter $c is lost silently!
class D extends A {
protected $d;
function __construct($a,$b,$c,$d) {
$this->a = $a;
$this->b = $b;
$this->c = $c;
$this->d = $d;
}
}
D::createOrUpdate("rock","this","now");
Error: Throws ArgumentCountError
class E extends A {
function __construct($b,$c) {
$this->a = "Lorem";
$this->b = $b;
$this->c = $c;
}
}
D::createOrUpdate("rock","this","now");
Error: Works but will behave completely unexpected.
Now my question is: Can I use some reflection within createOrUpdate()
in order to check if the current subclass called is implementing the constructor correctly? How would you handle this if somebody else may implement further subclasses within the hierarchy?
How about if you implement interface to your A class?
This will force every extending class to either not have constructor or implement the one matching on class A or
PHP Fatal error: Declaration of B::__construct($a, $b) must be compatible with interfaceA::__construct($a, $b, $c)
will be thrown.You can also add
public static function createOrUpdate($a, $b, $c);
to the interface to force all extending classes to implement such method.