There is some degree of overlap between them.
Unlike type annotations, type declarations are part of the language itself and are enforced at runtime. If you use a type declaration to indicate that the function accepts (or returns) an int , and you pass (or return) an array, you will receive an error message. If you pass a float, PHP will try to convert it for you, if possible, and otherwise, otherwise (weak mode) or always throw an error (strict mode). Type declarations are also checked in inheritance and in the implementation of interfaces, which prevents the use of incorrect types in your implementations. Annotations, on the other hand, are merely comments and are not executed at runtime. Since type declarations are enforced, you will ideally always use them wherever possible.
Because type annotations and type declarations can serve as documentation for a parameter or return type, the annotation is redundant if you have a type declaration. But keep in mind if you use tools like an IDE or a documentation generator that do not yet recognize type declarations, and you will need to keep annotations. You should also consider that you can provide a parameter description or return value in the annotation for documentation that you cannot do with the type declaration, and sometimes you can also specify a more precise type in the annotation (for example, an int[] declaration annotation vs array or subclass of the class returned by the method you override). However, if none of them apply, and your annotations do not contain more information than in the function signature ( function foobar(int $foo, string $bar): Qux string function foobar(int $foo, string $bar): Qux ), the annotations are a waste of space.
So, in summary: always use type declarations. As for annotations, use them if you need (equipment) or they provide additional information.
source share