36

I am using Eclipse PDT and I want to annotate a local variable using Phpdoc.

All I see is that I can annotate the variables/properties of a class using @var or even @property, but how is this possible for a local variable?

How can I do something like this?

function foo(){
  /** @var Stock $a */
  $a->save();
}
1
  • 1
    Documentation/contracts generally only applies to exposed interfaces - e.g. fields and methods. Commented Jan 2, 2013 at 0:38

2 Answers 2

75

The Phpdoc standard does not cover these annotations (it only cover class properties with the @var tag); however, it is perfectly possible in Eclipse (e.g. PDT):

/* @var $variable Type */
 ^         ^        `--- type
 |      variable           
 |
 `--- single star

This also works in all other PHP IDEs like Netbeans or Phpstorm which is useful if you exchange your code with others.

Example Code:

<?php

/* @var $doc DOMDocument */
$doc->
 

Example Screenshot (Eclipse PDT (Indigo)):

Eclipse PDT (Indigo)

Related Question & Answers:

Sign up to request clarification or add additional context in comments.

11 Comments

I tried like this but it still fails: function foo(){ /* @var $a Stock */ $a->save(); }
@tzortzik What do you mean with "it fails"? You know, that it is only for inspection?
@tzortzik: Which editor plugin are you using in Eclipse to edit PHP files? E.g. for me this perfectly works with code-completition in PDT (hammering CTRL + SPACE). Give Eclipse/DLTK some time to update, probably you need to place the comment in the line above the variable where you want to use it. At least that is how I normally do it. Not to the left of it but above. Like in your question.
@hakre: I did everything you said until my first post. I tried everything. I use the latest version of Eclipse PDT. I updated everything that is related to PHP and Eclipse.
@tzortzik: I can not explain why it does not work for you. I just create an example code and added a screenshot how it works for me in Eclipse Indigo PDT.
|
6

This is an old question, but only for reference. You must include the Use statement for the Type in current file in order to @var annotation work

<?php
use YourVendor\YourBundle\Entity\ProductType;

...

/* @var $product_type ProductType */
$foo = $product_type->getName();

2 Comments

/* @var $product_type \YourVendor\YourBundle\Entity\ProductType */ works too
@marcel-djaman: Yes, of course. My answer points to the fact that it is necessary indicate the fully qualified name of the Type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.