I want to have a variable that is passed to my function as either an array or a string and have them optional. Here is the sample function:
function myFunction(string $msg = '' || array $msg = []) { // This is line 9
if(is_string($msg)) {
echo "I'm a string";
} else if (is_array($msg)){
echo "I'm an array";
}
}
Is this possible? I can’t find anything that specifically shows this. When I try to run this function on a test page I get the following error:
Parse error: syntax error, unexpected variable "$msg", expecting "("
in /Path/To/My/File/test.php on line
9
I have looked at the php manual for function arguements: https://www.php.net/manual/en/functions.arguments.php and it states:
Information may be passed to functions via the argument list, which is
a comma-delimited list of expressions. The arguments are evaluated
from left to right, before the function is actually called (eager
evaluation).
So why wouldn’t what I wrote work?
2
Answers
It is posible, but the default value must be one of the types in your union type (Available since PHP 8.0):
Output:
Note: Composite Types are only available in PHP>=8. To accomplish this in PHP<8 you would have to omit the type declaration completely, and implement the check yourself. Eg:
Though if you’re trying to accommodate "one or more" in a simplified manner I would suggest something like the following instead:
Which has the additional benefit of ensuring that all the array members are strings, along with being much easier to maintain.