Page MenuHomePhabricator

How to handle the nullable operator on multi type lists in code
Open, Needs TriagePublic

Description

The nullable operator ? was added with php7.1

How to use it on multi type lists?

/**
 * @param ?string|int $a1
 * @param ?string|?int $a2
 * @param string|?int $a3
 * @param string|int|null $a4
 */

There is no difference to have $a a nullable string or a nullable int. It seems wrong to use ? here.
Or it is better to have ? on each type? Or use null as extra type?

How the php doc generator handle this case? (doxygen/phpDoc)

All the cases the code style does not want could be avoided by using a codesniffer

I would prefer variante 4

Event Timeline

Uh, nice suggestion! I agree. All examples that include a ?… and a …|… the same time are not wrong, but very confusing. I would love to converted them all to …|null.

I also prefer the 4th version, and agree with Thiemo above: while not wrong, 1 and 3 are a bit confusing, and 2 looks very redundant. I wonder if there's a standard about that.

DannyS712 subscribed.

Sounds good to me, would probably need to go in FunctionCommentSniff with the handling of nullable parameters if there is no standard upstream

the rfc for union types in php8 gives a good answer -https://wiki.php.net/rfc/union_types_v2#nullable_union_types

Union types and the ?T nullable type notation cannot be mixed. Writing ?T1|T2, T1|?T2 or ?(T1|T2) is not supported and T1|T2|null needs to be used instead.

That means for me, the ? in existing union types should be autofixed to |null, if the null is already part of the union type the ? should be removed.

There's a broader discussion to have here (about use of the nullable operator in Doxygen blocks at all), so I've started a thread: https://www.mediawiki.org/wiki/Topic:Wz68j77ejxgi4qq7