88

Is there a way to hint WebIDE that a variable has some type? I have to iterate an array of objects, and there's no auto-completion available. This helps in ZendStudio:

/* @var ClassName $object */

I know there's a feature in JetBrains to declare an array of objects:

/**
 * @return ClassName[]
 */

But this works only with function's return type.

Makoto
  • 104,088
  • 27
  • 192
  • 230
kolypto
  • 31,774
  • 17
  • 105
  • 99

2 Answers2

163

/* @var ClassName $object */ is a non-valid PHPDOC comment and is not parsed in the current version of Web IDE. Use double asterisks to make it work:

/** @var ClassName $object */

Also, you can annotate $array in foreach($array as $var) with /** @var ClassName[] $array */ and $var type will be deduced automatically.

Alexey Gopachenko
  • 7,458
  • 3
  • 27
  • 25
  • didn't know about the square brackets notation – sanya Aug 18 '14 at 16:56
  • 2
    Related question: My PHP class uses magic getter for a variable and I want to bind that getter variable to a Class object, any idea how to do that? As I cannot define the variable in my class. – Sanket Sahu Nov 14 '14 at 12:50
  • Wow.. just googled for fun and really no hope that this will actually be a thing.. I never was so wrong in my life and I am happy that I was wrong! This feature is so cool, thanks! :) – Cagatay Ulubay Feb 05 '16 at 14:03
  • Very relevant for $this->getUser() inside a controller in a Symfony app – Guillaume Harari May 12 '22 at 08:55
35

As already pointed out, PhpStorm will use regular phpdoc blocks:

/** @var ClassName $object */

However, since 2.1 it also supports Netbeans/Eclipse/Zend @var annotations:

/* @var $object ClassName */

Please note the comment starts with /* rather than /** (thus it won't show up if you generate actual documentation with phpdoc). Also, the arguments are swapped, though PhpStorm accepts any order:

/* @var ClassName $object */

Last but not least, they can precede almost any arbitrary line of code (technically, phpdoc blocks are restricted to certain items).


Edit: as of 2019, Netbeans/Eclipse/Zend @var annotations seem to be mostly abandoned. NetBeans 11 no longer supports them and in general they aren't supported by other IDEs. I suggest to use the other syntax.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • Last archive of the introduction of this annotation style on former Netbeans owner Oracle's blog: https://web.archive.org/web/20200921104605/https://blogs.oracle.com/netbeansphp/defining-a-variable-type-in-comment – cachius Feb 10 '22 at 11:08
  • @ReinState Answer updated, thank you! – Álvaro González Feb 10 '22 at 11:12