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
Recommendations¶
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:
Interfaces¶
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
assume unknown
(a special, internal type that passes all checks).
Arrays¶
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 Type[]
syntax,
or the array<Type>
syntax; both are equivalent.
Type Reference¶
This is a reference of which types are supported in doc comments.
Type | Description |
---|---|
boolean , Boolean , or
bool |
Value can be true , or false |
false |
Value can be only boolean false . This only
makes sense in combination with another
type, e.g. false|string . |
integer , or int |
Value is an integer. |
float , or double |
Value is a float. |
string |
Value is a string. |
null |
Value is null. This only makes sense in
combination with another type, e.g.
string|null . |
callable |
Value is a callable, that is a string ,
array , or object that implements
__invoke . |
void |
Value is of no type. This type is solely reserved for return type of methods without a body. |
self , static , or
$this |
Value is an object. This is reserved for
cases where you return $this from a
method, and is resolved to the class on
which the method is being called. |
array |
Value is an array with arbitrary keys/values. |
array<T> , T[] |
Value is an array with integer keys, and elements of type T where T can be any available type. |
ClassName |
Value is an object of the given class. |
A|B |
Value is of type A , or type B where
A , and B are any available type. |
mixed , or * |
Value is of any available type. We encourage you to avoid this type whenever you can. |