Re: [RFC] Null Coalescing Assignment in Method Signature

From: Date: Thu, 21 Jan 2021 22:22:41 +0000
Subject: Re: [RFC] Null Coalescing Assignment in Method Signature
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-112959@lists.php.net to get a copy of this message
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]

« previous php.internals (#112959) next »