How to use more than two types in function parameters?

4

Suppose the following function in PHP:

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

In theory, the parameter $callback must be an array , but can also be accepted as string . How do I accept both arrays and strings ?

    
asked by anonymous 29.12.2017 / 22:07

1 answer

3

Do not put the type. PHP is essentially a dynamic language, you do not need to note the type:

function parse(string $text, $callback) {
    if (gettype($callback) == "array") echo "é um array\n";
    else echo $callback;
}
parse("xxx", array("yyy"));
parse("xxx", "yyy");

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

I've really liked this solution, but other than 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.

    
29.12.2017 / 22:17