Type Hinting for Class Members?
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!
Please sign in to leave a comment.
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:
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:
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.