Topic on Manual talk:Coding conventions

Consistency of nullable types in PHP documentation and type hints?

3
Jdforrester (WMF) (talkcontribs)

In our codebases we have a mix of old-style (Class|null) and new-style (?Class; "new" in PHP 7.1) annotations in our Doxygen blocks and so on; how would people feel about us standardising on one of these rather than having both?

In T250734 there has been some discussion about how to handle the use of nullable types in the more complicated scenario of multiple types (i.e. Class|SecondClass|null etc.), but I don't think we've had an up-front conversation at all about use of the nullable operator yet, and certainly our code is a messy mish-mash of multiple types. (Indeed, I've even seen ?Class $foo = null used.)

Given the lack of a way to handle these for multiple types, I think we should standardise on old-style annotations everywhere to create consistency for now, and write a rule (ideally with an auto-fixer) for the codesniffer tool.

Thoughts?

Duesentrieb (talkcontribs)

Only the new style types work for type hints. Using ?Foo in the type hint and Foo|null in the doc block seems annoying and inconsistent. I'd opt for using the new style everywhere.

By the way: ?Foo $foo = null is different from Foo $foo = null and from ?Foo $foo: The first means "it's optional, but can be null explicitly", the second means "it'S optional, but shouldn't be null if given explicitly", and the third one means "it's required to be provided, but can be null".

Tgr (WMF) (talkcontribs)

+1 for using old-style for consistency. PSR-5 (a draft, and a quite old one at that, but the closest thing to a standard the PHP world has today) has no ?; combining it with unions is illegal in PHP 8, which we'll eventually adopt, at which point it would be very confusing to advertise a mistake in our type docs; and having to switch between ? and |null as types get added / removed would be annoying.

By the way: ?Foo $foo = null is different from Foo $foo = null and from ?Foo $foo: The first means "it's optional, but can be null explicitly", the second means "it'S optional, but shouldn't be null if given explicitly", and the third one means "it's required to be provided, but can be null".

That sounds logical but isn't how PHP actually works. The first two are identical, as a null default implicitly makes the parameter type nullable. The semantics also depend on the context: f(Foo $foo = null, Bar $bar) and f(?Foo $foo, Bar $bar) are identical (though only for B/C with pre-? legacy code).

Reply to "Consistency of nullable types in PHP documentation and type hints?"