BeetleJuice BeetleJuice - 2 months ago 11
PHP Question

PhpStorm: how to tell the var type of an array member?

I use

PhpStorm 2016.2.1
IDE. I have a typed array (all members will be of the same, known class) and I'd like the IDE to know the type so I it can help me out with autocomplete/intellisense.

class MyClass{
/**
* @var array
*/
public $userArray;

public addUser($uid){ $this->$userArray[$uid] = new User($uid); }

public processUser($uid){

$oUser = $this->$userArray[$uid];
//since the PHP array can contain anything, the IDE makes
//no assumption about what data type $oUser is. How to let it
//know that it's of type User?
}
}


I have tried...

/**
* @var User
*/
public $oUser = ...;


And also

/**
* @type User
*/
public $oUser = ...;


So far, the only thing I've gotten to work is to use getter functions:

/**
* @return User
*/
function getUser($uid){ return $this->$userArray[$uid]; }

function processUser($uid){
//now the IDE knows the type of $oUser
$oUser = $this->getUser($uid);
}


But slowing down the script with unneeded function calls just to get better IDE support seems like a bad idea.

Any idea how I can let PhpStorm know the type of a variable? Or even better: how to tell it which type an array will contain in the
PHPDoc
metadata for that array?

Answer

For class variables, as you know, you can simply do

@var User

For local variables, it's not officially a supported format, but you must also specify the variable name:

@var User $oUser

Specific to PHPStorm, you'll need to use double asterisks (I think it's the only IDE that needs it, please consider that):

/** @var User $oUser */

See the PHPDoc manual for more info

Comments