I have a class in PHP like so:
class ParentClass {
function __construct($arg) {
// Initialize a/some variable(s) based on $arg
}
}
My way of doing it (tested in PHP 7.1):
class ParentClass {
public function __construct(...$args) {
print 'Parent: ' . count($args) . PHP_EOL;
}
}
class ChildClass extends ParentClass {
public function __construct(...$args) {
parent::__construct(...$args);
print 'Child: ' . count($args). PHP_EOL;
}
}
$child = new ChildClass(1, 2, 3, new stdClass);
//Output:
//Parent: 4
//Child: 4
Test it https://3v4l.org/csJ68
In this case, the parent and the child have the same constructor signature. It also works if you want to unpack your arguments in the parent constructor:
class ParentClass {
public function __construct($a, $b, $c, $d = null) {
print 'Parent: ' . $a . $b . $c . PHP_EOL;
}
}
class ChildClass extends ParentClass {
public function __construct(...$args) {
parent::__construct(...$args);
}
}
$child = new ChildClass(1, 2, 3);
//Output: Parent: 123
Test it https://3v4l.org/JGE1A
It is also worth noticing that in PHP >= 5.6 you can enforce types for variadic functions (scalar types in PHP >= 7):
class ParentClass {
public function __construct(DateTime ...$args) {
//Do something
}
}