So, in PHPDoc one can specify @var
above the member variable declaration to hint at its type. Then an IDE, for ex. PHPEd, will know what type of object it's working with and will be able to provide a code insight for that variable.
<?php
class Test
{
/** @var SomeObj */
private $someObjInstance;
}
?>
This works great until I need to do the same to an array of objects to be able to get a proper hint when I iterate through those objects later on.
So, is there a way to declare a PHPDoc tag to specify that the member variable is an array of SomeObj
s? @var
array is not enough, and @var array(SomeObj)
doesn't seem to be valid, for example.
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
tocurrent()
and rest of theIterator
andArrayAccess
-methods which return values.Boom! No need in
/** @var SomeObj[] $collectionObj */
overforeach
, 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:
What useful i was going to add posting this answer
In my case
current()
and rest ofinterface
-methods are implemented inAbstract
-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:
Now, usage of classes:
Once again: I suspect not all IDE support it, but PhpStorm does. Try yours, post in comment the results!
In NetBeans 7.0 (may be lower too) you could declare the the return type "array with Text objects " just as
@return Text
and the code hinting will work:Edit: updated the example with @Bob Fanger suggestion
and just use it:
It is not perfect but it is better then just to leave it just "mixed", which brings no value.
CONS is you are allowed to tread the array as Text Object which will throw errors.
I've found something which is working, it can save lives !
In the PhpStorm IDE from JetBrains, you can use
/** @var SomeObj[] */
, e.g.:The phpdoc documentation recommends this method:
Use:
when typehinting inline variables, and
for class properties.
Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:
The best you can do is say,
I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.