skip to Main Content

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


  1. It is posible, but the default value must be one of the types in your union type (Available since PHP 8.0):

    function myFunction(string|array $msg = [])
    
    //OR
    
    function myFunction(string|array $msg = '')
    
    Login or Signup to reply.
    1. Composite Types: https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.composite
    2. Nullable Types: https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.nullable
    function myFunction(string|array $msg = NULL) {
        if( is_null($msg) ) {
            // do a default thing?
        }
        var_dump($msg);
    }
    
    myfunction();
    myfunction('foo');
    myfunction(['foo']);
    

    Output:

    NULL
    string(3) "foo"
    array(1) {
      [0]=>
      string(3) "foo"
    }
    

    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:

    function myFunction($msg = NULL) {
        if( ! in_array(gettype($msg), ['string', 'array', 'NULL']) ) {
            throw new Exception('Parameter msg not of an acceptable type.');
        }
        var_dump($msg);
    }
    

    Though if you’re trying to accommodate "one or more" in a simplified manner I would suggest something like the following instead:

    function handleOne(string $msg) {
        echo $msg . PHP_EOL;
    }
    
    function handleMany(array $msgs) {
        foreach( $msgs as $msg ) {
            handleOne($msg);
        }
    }
    
    handleOne('first');
    handleMany(['second', 'third']);
    

    Which has the additional benefit of ensuring that all the array members are strings, along with being much easier to maintain.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search