Well this may be trivial. But I am stuck.
I need to pass an argument to a function but need to type hint it like so:
private function printUsers(Collection<User> users) {
foreach($users as $user) {
print($user->fullName)
}
}
How do I type hint this collection, because I want a collection of a specific model?
CodePudding user response:
Generics are not supported in PHP. However if you are using certain IDEs (at least PhpStorm does this) you can put the generic in the docblock:
/**
* @param Collection<User> $users
*/
private function printUsers(Collection $users) {
foreach($users as $user) {
print($user->fullName)
}
}
However this will still not work because Laravel has not type-hinted the collection as generic (not yet at least).
The general way to resolve this (again using a docblock) is to do the "hacky" typehint of:
/**
* @param Collection|User[] $users
*/
private function printUsers(Collection $users) {
foreach($users as $user) {
print($user->fullName)
}
}
This will typehint $users as an array accessible variable with User members, which is probably close enough for your needs but:
(a) completion only works in IDEs that support the User[] syntax
(b) It only works when iterating i.e. it's not a true generic
CodePudding user response:
You can't, unless you create a UserCollection type. Seems you're trying to apply some other OOP lang concepts (e.g. Java).
An easy way to do that, is maintain the Collection parameter type, and evaluate the argument inside function like:
private function printUsers(Collection $users) {
foreach($users as $user) {
try {
$user = (User) $user; // Not strictly necessary.
print($user->fullName);
} catch (Exception $e) {
// Resolve exception
}
}
}
