Do not type. PHP is essentially a dynamic language, you do not need to type:
function parse(string $text, $callback) {
if (gettype($callback) == "array") echo "é um array\n";
else echo $callback;
}
parse("xxx", array("yyy"));
parse("xxx", "yyy");
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I’ve liked this solution a lot, but other than in very simple things and it makes a lot of sense to do so, today I prefer to create a separate function to deal with another type of data.
In PHP 8 you can use the type mixed
to say that it accepts different types and thus maintain typing and flexibility. In practice it does the same, but in the future perhaps the language will no longer accept without the type.
Knowing that can be two different types can use one kind of union leaving only these two. It would still require a if
to know which came and the solution of different functions remains better.
Why the negative?
– Luiz Felipe