Annotating Types via PHP Doc Comments¶
PHP Analyzer generally infers types just by looking at your code. Besides that many PHP projects also make use of doc comments to enhance type inference of IDEs and static analysis tools. This document explains which doc comments are being considered by PHP Analyzer.
Supported Doc Comments¶
PHP Analyzer currently reads the following doc comments:
@param [type] $[paramName]for functions/methods
@return [type]for functions/methods
@var [type] $[variableName]everywhere
@type [type] $[variableName]everywhere
Generally, it is not necessary to add doc comments to each and every element, PHP Analyzer is smart enough to infer most types for you. In some cases, we explicitly recommend to add doc comments though:
Since interfaces have no code from which a type can be inferred. We recommend
that their methods are always annotated. For parameters, a comment is not strictly
necessary if it is already covered by a type hint. Return types should always
be specified via a comment, even if the method does not have a return value in
which case you can use the
void type. If no type is specified, we will
unknown (a special, internal type that passes all checks).
PHP itself provides the generic
array type hint. Unfortunately, that does
not allow to specify what the types of its values are. Therefore, we encourage
to specify a more specific type via comments using either the
array<Type> syntax; both are equivalent.
This is a reference of which types are supported in doc comments.
||Value can be
||Value can be only boolean
||Value is an integer.|
||Value is a float.|
||Value is a string.|
||Value is null. This only makes sense in
combination with another type, e.g.
||Value is a callable, that is a
||Value is of no type. This type is solely reserved for return type of methods without a body.|
||Value is an object. This is reserved for
cases where you return
||Value is an array with arbitrary keys/values.|
||Value is an array with integer keys, and elements of type T where T can be any available type.|
||Value is an object of the given class.|
||Value is of type
||Value is of any available type. We encourage you to avoid this type whenever you can.|