Reputation: 4783
I was wondering if there is any difference in using type hint in method parameters, such as:
function xyz (UserRepository $repo)
and doing the same stuff with annotations:
function xyz ($repo)
/* @var UserRepository $repo */
Upvotes: 3
Views: 1903
Reputation: 11
In addition to what Gordon said, Laravel uses type-hints for automatic injection: https://laravel.com/docs/5.5/container#automatic-injection
Upvotes: 1
Reputation: 317197
Using a type hint like
function xyz (UserRepository $repo)
is an instruction that the compiler will understand and react to. This means, PHP will raise an error when you try to pass anything that is not a UserRepository
.
Quoting from the PHP Manual:
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
Using the "annotation" is just documentation. It's just a hint for your IDE and a developer. It has no functional meaning when executing PHP. A user would be able to pass whatever he wants to the function, e.g.
$somethingElse = new SomethingElse;
xyz($somethingElse);
This would work, but then it will fail when trying to access methods on $somethingElse
that belong to the UserRespository
. With a type hint, you would fail early.
Note: I put annotation in quotes because it's not really an annotation as you know from other languages, like Java. PHP doesn't have annotations as of 7.2. Userland implementations exist though.
Prefer real type hints.
This is not a Laravel specific thing by the way. Type Hints are a native PHP feature.
Upvotes: 5