Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hinting and multiple constructors

Tags:

php

php-7

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?

like image 656
OptimusCrime Avatar asked Jul 21 '15 14:07

OptimusCrime


1 Answers

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.

like image 97
bwoebi Avatar answered Oct 22 '22 08:10

bwoebi