As DanielaWaranie mentioned in her answer - there is a way to specify the type of $item when you iterating over $items in $collectionObject: Add @return MyEntitiesClassName
to current()
and rest of the Iterator
and ArrayAccess
-methods which return values.
Boom! No need in /** @var SomeObj[] $collectionObj */
over foreach
, and works right with collection object, no need to return collection with specific method described as @return SomeObj[]
.
I suspect not all IDE support it but it works perfectly fine in PhpStorm, which makes me happier.
Example:
class MyCollection implements Countable, Iterator, ArrayAccess {
/**
* @return User
*/
public function current() {
return $this->items[$this->cursor];
}
//... implement rest of the required `interface` methods and your custom
}
In my case current()
and rest of interface
-methods are implemented in Abstract
-collection class and I do not know what kind of entities will eventually be stored in collection.
So here is the trick: Do not specify return type in abstract class, instead use PhpDoc instuction @method
in description of specific collection class.
Example:
class User {
function printLogin() {
echo $this->login;
}
}
abstract class MyCollection implements Countable, Iterator, ArrayAccess {
protected $items = [];
public function current() {
return $this->items[$this->cursor];
}
//... implement rest of the required `interface` methods and your custom
//... abstract methods which will be shared among child-classes
}
/**
* @method User current()
* ...rest of methods (for ArrayAccess) if needed
*/
class UserCollection extends MyCollection {
function add(User $user) {
$this->items[] = $user;
}
// User collection specific methods...
}
Now, usage of classes:
$collection = new UserCollection();
$collection->add(new User(1));
$collection->add(new User(2));
$collection->add(new User(3));
foreach ($collection as $user) {
// IDE should `recognize` method `printLogin()` here!
$user->printLogin();
}
Once again: I suspect not all IDE support it, but PhpStorm does. Try yours, post in comment the results!