On 21/01/2021 21:28, Larry Garfield wrote:
I'm unclear why you'd allow null at all then.  If you want $bar to be optional, 
and to be an empty array if not specified, then just do:

function foo(array $bar = []) { ... }

At that point, the only thing adding ?array does is allow you to explicitly 
pass null, presumably because it has some meaning to your function.  If you 
don't want that, don't allow it.


I'm not totally sold on the idea, but I can definitely see why it would be useful.

I think a more complex example might show it more clearly:

function frobulate(int $id, int $flags = FROB_CLOCKWISE | FROB_MEDIUM_SPEED) {
   // ...
}

Now try to write a function that wraps this in some way, and wants to retain the default for the $flags parameter without hard-coding it. In order to get the default, you have to call the function with fewer arguments:

function log_and_frobulate(int $id, int $flags = null) {
   log_stuff($id);
   if ( $flags === null ) {
        return frobulate($id);
   } else {
       return frobulate($id, $flags);
   }
}

(There's probably other approaches using the "..." argument unpacking operator, but off the top of my head, I can't think of any that avoid the if completely.)

If the argument was specified with $flags??=... instead of $flags=... the wrapper doesn't need the extra branch:

function log_and_frobulate(int $id, int $flags = null) {
   log_stuff($id);
   return frobulate($id, $flags);
}


Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to