There is some degree of overlap between these.
Unlike type annotations, type declarations are part of the language itself, and enforced by the language runtime. If you use a type declaration to specify that a function takes (or returns) an int
, and you pass in (or return) an array, you'll get an error. If you pass in a float, PHP will try to convert it for you if possible and error otherwise (weak mode), or always throw an error (strict mode). Type declarations are also checked in inheritance and when implementing interfaces, preventing you using the wrong types in your implementations. Annotations, on the other hand, are merely comments and are not enforced by the runtime. Because type declarations are enforced, you would ideally always use them where possible.
Since both type annotations and type declarations can serve as documentation of a parameter or return type, an annotation is redundant if you have a type declaration. But bear in mind whether you are using tools, such as an IDE or documentation generator, that don't recognise type declarations yet, and would need you to retain the annotations. You should also consider that you can provide a description of a parameter or return value in an annotation for documentation, which you can't do with a type declaration, and there are also sometimes cases where you can specify a more precise type in an annotation (e.g. int[]
annotation vs array
declaration, or a subclass of the class returned by the method you are overriding). However, if neither of these apply, and your annotations provide no more information than is in the function signature (the function foobar(int $foo, string $bar): Qux
line), annotations are a waste of space.
So, in summary: always use type declarations. As for annotations, use them if you need to (tooling) or they provide additional information.
DateTime
objects? – Jemine