'How to make autocomplete work in foreach php loop? (vscode, intellisense)
I'm using vscode, and php extension pack (it contains mostly used extensions). I would like to use intellisense in this foreach loop:
foreach ($list_of_objs as $obj) {
/* @var $obj my_class_name */
// I want to go to definition of obj_method()
// with F12 but it's not working
// also auto-complete is not working
$obj->obj_method();
}
Please give some advice, if you can solve this issue. I found solution for Zend Studio but not for vscode.
Is there an extension to support doc-block type hinting anywhere in the code? Would be really nice:
/** @var my_class_name */
$my_variable;
As far as I know, only place for variable types is in function declaration in php7. PHP IntelliSense also understands
$obj = new ClassName;
(bless them for at least that ...)
Solution 1:[1]
You were trying good old Eclipse/Zend type annotations:
/* @var $obj my_class_name */
$obj->obj_method();
There aren't many editors that support them anymore. The de-facto standard as of today seems to be:
/** @var my_class_name $obj */
$obj->obj_method();
I may be wrong but I believe that PHP IntelliSense does not support either anyway (please try and report back). I can confirm that PHP Intelephense does support the latter.
Solution 2:[2]
As after a lot of search I did not find an easy solution for this, I came up with this working solution:
In your class create a static function
/**
* Returns the instance itself for Code completion
* @return ClassName
*/
public static function self($instance) {
return $instance;
}
With that you can have an instance with type like this:
foreach ($list_of_objs as $obj) {
$obj = ClassName::self($obj);
$obj->obj_method()
}
It would be better if an annotation in the foreach
worked but at least it is a way to use code completion at all.
Solution 3:[3]
try this, it's work for me
add this to top of the foreach
/** @var post $post */
for example
/** @var post $post */
foreach($res_class as $post)
{
// you can use auto complete in vscode
$post
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ãlvaro González |
Solution 2 | |
Solution 3 | MOJTABA APK |