stefmikhail stefmikhail - 1 year ago 86
PHP Question

Why declare PHP variable type in a comment?

I'm fairly new to PHP, and I just started using NetBeans to develop my PHP code.

Out of the blue, as I entered a variable in a query, a dialog popped up and asked me to complete a comment to hold the variable type. I did some investigation and found that this seems to be a popular feature of NetBeans, but I couldn't find any information to explain to me why this was the case.

Why would someone want to place a PHP variable's type in a comment? Is it for development use, or does it actually benefit the code itself? Is it integral, or optional?

Thanks in advance, and I apologize if my ignorance astonishes you.

Answer Source

Adding the type in a @var tag inside your method's comment will allow NetBeans to show you code completion. This of course is optional but it is always a good idea to fully document your code.

Edit: A tip for NetBeans to auto-generate the comments for you is to use the /** expansion. To do this, simply place the cursor above the property or method you want to document and type /** and then press the ENTER key. This will expand a phpDoc style comment and add the appropriate tags.

Edit 2: You can use the @var tag on a property and you can use the @param tag on a method to achieve the same effect with parameters passed into a method.

Use of the @var tag on a property will give you code hints while using the property any where it is visible:

 * @var My_Type
private $_myProperty;

Use of the @param tag on a method will give you code hints while using the parameter inside the method:

 * @param My_Type $obj 
public function myMethod($obj) {


Another way to achieve a similar effect while also providing a modicum of type safety is to use PHP's type hinting mechanism:

public function myMethod(My_Type $obj) {


Notice that this method has the type specified in the method signature. NetBeans will now provide the same code completion inside the method that is available using the @param tag and PHP will produce a E_RECOVERABLE_ERROR if the type passed into the method is not the same type that was specified. See PHP's documentation regarding errors and how to handle them if your interested in learning more about the above error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download