How to get intellisense working with phpStorm when passing object to function or iterating

I have an object with getters and setters but I'm loosing intellisense on that object when I pass it to a function or while iterating through a array of these objects.

For example:

...
$personA = new Person(..);
$age = $personA->getAge();  // intellisense works.

$personArray = array($personA, $personB, .. );
foreach($personArray as $aPerson){
   $aPerson->getAge();   //  no intellisense here
}

doSomething($personA); 



function doSomething($person){
   $person->getAge()         //  no intellisense here
   ...
}

What am I missing here?

Do I need to make a change to code(casting.. etc), Missing a phpStorm setting? Maybe it's not possible?

Answers


For the first foreach case it is not (yet) possible out of the box, however you can typically hint that:

$personArray = array($personA, $personB, .. );
foreach ($personArray as $aPerson) {
   /* @var $aPerson Person */
   $aPerson->getAge();  // now with code-completition
}

Which is doing the type-hinting on the variable that is taking the iteration. Alternatively you can also do the type-hinting on the array variable:

/* @var $personArray Person[] */
$personArray = array($personA, $personB, .. );
foreach ($personArray as $aPerson) {
    $aPerson->getAge();  // now with code-completition
}

For your second case, you can add PHP type-hinting (which I recommend):

function doSomething(Person $person) {
   $person->getAge() //  now with code-completition
   ...
}

This also ensures that you can only pass values that are of that type. See as well Type Hinting Docs and Interfaces Docs.

The other solution for the second case is to also document the parameter in the docblock of the function:

/**
 * @param Person $person
 */
function doSomething($person) {
   $person->getAge() //  now with code-completition
   ...
}

Some Related Answers:


While the PPHDoc blocks from @hakre answer is working in PHPStorm, the correct form would be type followed by variable name like this

/** @var Person $aPerson */

and that

/** @var Person[] $personArray */

These will work in PHPStorm and phpDocumentor.

Source: http://www.phpdoc.org/docs/latest/references/phpdoc/tags/var.html


Need Your Help

SQL count rows in a table

sql-server count rows database-table

I need to send a SQL query to a database that tells me how many rows there are in a table. I could get all the rows in the table with a SELECT and then count them, but I don't like to do it this wa...

Changing language on iOS 8.1 simulator does not work

ios localization ios-simulator xcode6.1 ios8.1

If I change the language on an iOS 8.1 simulator to anything and try to detect this from code with