Menu

How to properly annotate static method call from variable class name in PHP?

php doc phpdoc ide phpstorm

I have few code fragments, where class name is as variable, ie string, and i call static method on it. Honestly, before tried it I didn't even know if that was possible;)

Example:

assert(class_exists($formClass));
assert(is_a($formClass, WidgetInterface::class, true));
$form = $formClass::widget([
    'model'=> $model
]);

The assertions are added to ensure that $formClass contains in fact existing class name.

The code above creates instance of $formClass, with factory method widget. The code works properly, however my IDE, in this case PhpStorm complain with error message:

Method widget not found in string

To overcome this issue, simply instruct IDE that $formClass is instance of class having widget method:

assert(class_exists($formClass));
assert(is_a($formClass, WidgetInterface::class, true));
/* @var $formClass Widget */
$form = $formClass::widget([
    'model'=> $model
]);