How to use more than two types in function parameters?

Asked

Viewed 81 times

3

Suppose the following function in PHP:

 function parse (string $text, array $callback) {
   # ...
 }

In theory the parameter $callback must be a array, but it can also be accepted as string. How do I get him to accept so much arrays as strings?

  • Why the negative?

1 answer

3


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.