Autocomplete for array elements

Is it possible to do something like this?

class Test{
     public function testFunction()
     {
          return true;
     }
}


$array[0] = new Test();

$class = $array[0];

$class->{caret}                     ==> Autocomplete pops up here showing Test class' methods.

6 comments

Hi Bill,

Try adding phpdoc comment before variable assignment, so it looks like this:

/** @var Test[] $array */
$array[0] = new Test();
$class = $array[0];
$class->
0

Wow, I didn't know that :) Thanks.
What if array has different classes as elements. Like

$array[] = new Class1();
$array[] = new Class2();

0

I do not think that this can be achieved in any way for such scenario. Unless you will write a phpdoc comment before each variable assigment, like:

$array[] = new Class1();
$array[] = new Class2();

/** @var Class1 $class1 */    
$class1 = $array[0];
/** @var Class2 $class2 */    
$class2 = $array[1];

But's that is wrong in my opinion -- why do you need the $array in first place then?

The problem here is that IDE cannot reliably evaluate which class instance you are working with right now -- this can only be properly done by PHP interpreter itself during script execution.

0

I don't. I just trying to find out how autcomplete can be used for arrays. For example what if a class method returns an array of object. e.g
{code source="php"}
class Test()
{
     public function testMethod()
     {
          $array = array();
          for ($i=0; $i<10;$i++){
               $array[] = new AnotherClass();
          }
          return $array;
     }
}


$class = new Test();
$returnArray = $class->testMethod();

$anotherClass = $returnArray[0]

$anotherClass->{caret}       -> AutoComplete here.

{code}

0

In this particular example this can be acheived in pretty much the same way as in original reply. Like this:

class AnotherClass
{
    public function testFunction()
    {
        return true;
    }
}

class Test
{
    /**
     * @return AnotherClass[]
     */
    public function testMethod()
    {
        $array = array();
        for ($i=0; $i<10;$i++){
            $array[] = new AnotherClass();
        }
        return $array;
    }
}

$class = new Test();
$returnArray = $class->testMethod();
$anotherClass = $returnArray[0];
$anotherClass->

or like this:

class AnotherClass
{
    public function testFunction()
    {
        return true;
    }
}

class Test
{
    public function testMethod()
    {
        $array = array();
        for ($i=0; $i<10;$i++){
            $array[] = new AnotherClass();
        }
        return $array;
    }
}

$class = new Test();
/** @var AnotherClass[] $returnArray */
$returnArray = $class->testMethod();
$anotherClass = $returnArray[0];
$anotherClass->

0

Good stuff!! Thanks for your help../.

0

Please sign in to leave a comment.