Type Hinting for Class Members?

Answered

Is it possible to use /** ... */ syntax (or any other method really) to specify what type of object a given class member is?  Not the class itself, just one member of that class.

I'm using the Yii2 framework and in Yii2, Yii::$app->user is typically an instance of \yii\web\User and everything works fine using these defaults.  However, there is a configuration setting you can modify to use your own implementation of \yii\web\User, so in my case I have this set to \common\components\User where I inherit from \yii\web\User and implement some of my own methods, overload some others, etc.  The problem comes when I try to do:

Yii::$app->user->customMethod()

PhpStorm complains in this case because it expects Yii::$app->user to be an instance of \yii\web\User, not \common\components\User, so it doesn't know what customMethod() is.  I tried doing this:

/** @var \common\components\User Yii::$app->user */

But it doesn't look like this form of type hinting works for class members, only simple variables such as $foo or $bar.

 

Any help would be appreciated! 

0
2 comments

Hi there,

>But it doesn't look like this form of type hinting works for class members, only simple variables such as $foo or $bar.

That is correct -- only top level variable can be type hinted this way.

 

You can type hint class property etc ... but it can be done when declaring that class (e.g. using @property or when actually defining that property -- using @var). But since Yii is already defined .. I do not know what can be done here via PHPDoc.

I may suggest these:

  • Try Yii specific plugins -- maybe they can do this dynamically (as it can be done via plugin)
  • Ask such question on Yii forums -- you are more likely to find such answer there

 

The only other alternative via PHPDoc that I may suggest is to use intermediate variable which you can type hint via typical inline @var PHPDoc comment. Downside -- you need to introduce such intermediate variable for no "real" reasons (from code execution point of view). In any case:

/** @var \My\Class $user */
$user = Yii::$app->user;
$user->someMethod();
0
Avatar
Permanently deleted user

Thanks for the quick reply Andriy!  I was hoping there was some built-in method to accomplish this but the solution you provided works like a charm, so I'll just do that.

0

Please sign in to leave a comment.