0

This problem seemed obvious at first to me but I've been struggling for a while and I can't find any useful information on internet/stack overflow regarding this.

I have a function that looks like this :

myfunction(string $parameter, array $optionalParameter = []) {
}

and in my call, something like that :

myfunction('text', BOOL ?? $array);

The problem is that, from what I understand, passing null as the second argument isn't the same as having no second argument, so $optionalParameter isn't initialized (I use phpstan and it tells me that null is incompatible with array).

The only solution I can envision would be to duplicate the function call, but it's really not a good idea considering my actual function has way more than 2 parameters.

TLDR; I'm looking for a way to turn the return type of BOOL ?? $array from array|null to array|(nothing) if that makes sense

IMSoP
  • 89,526
  • 13
  • 117
  • 169
Rilves
  • 146
  • 7
  • A default value is only used if no argument was given for the parameter. If you want to pass `null` for your second parameter, use `?array` or `array|null` instead of `array`. Then, in the first lines of your function, use something like `$optionalParameter = (optionalParameter === null ? [] : optionalParameter)`. – Noah Boegli Jul 11 '22 at 13:35
  • that's exactly what I was doing, but a colleague told me that I could reduce this part. If you see no other solution, I guess it's impossible – Rilves Jul 11 '22 at 13:36
  • _"but a colleague told me that I could reduce this part"_ - Reduce what exactly? All you need to do is add a `?` in front of the `array $optionalParameter` in the function argument and then add one single line in the top of the function: `$optionalParameter = $optionalParameter ?? [];`. That would allow you to pass in an array, null or don't pass anything in. Not sure how to make it easier than that? If that's not what you're asking, then you need to update the question with some real examples – M. Eriksson Jul 11 '22 at 13:40
  • 1
    Since you're using PHP 8.1 you could use named arguments, although it's essentially the same issue. Null still counts as an argument. I don't see how it could be done otherwise (maybe by passing an empty array instead of null for the second parameter, it's not clear in your question if that is an option). – Noah Boegli Jul 11 '22 at 13:41
  • @M.Eriksson the idea was to remove the possibility of having "null". I did what Noah Boegli suggested, which is probably the closest solution to what I was aiming for. Thanks for the help – Rilves Jul 11 '22 at 13:58
  • _"the idea was to remove the possibility of having "null""_ - But the examples you've posted doesn't allow you to pass `null`, so now I'm more confused – M. Eriksson Jul 11 '22 at 14:02

0 Answers0