I've been looking into the new features for PHP7 and thought I might begin to ready my project for the new features it introduces, like scalar type hinting.
One of the first problems I encountered was my constructors in various classes. I have some generic contrustors that acts something like this:
public function __construct($data = null) {
if (is_numeric($data)) {
$this->controller->createById($data);
}
elseif (is_array($data)) {
$this->controller->createByArray($data);
}
elseif (strlen($data) > 0) {
$this->controller->createByUrl($data);
}
}
Introducing type hinting for this method will of course throw errors in all directions.
As far as I know PHP7 does not introduce support for multiple constructors. Are there any ways to get around this problem, or is this one of the limitations of the language?
Correct, that's one of the limitations of the language.
(and the strlen() > 0
anyway can't be checked via a type. That auto-casts to string… so your method allows everything but "", null and false?)
Generally, there is RFCs in draft to expand the typehinting of PHP in 7.1: https://wiki.php.net/rfc/union_types
That would allow you to write int | float | array | string $data = null
.
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