This comes up in Laravel a lot if you use Macros, but it's not exclusive to that. If you bind a closure to another object context, the nature of $this within the closure changes. But IDEs don't recognize that, and don't offer the appropriate auto-fill options. It still thinks the context is that of the class the closure is defined in.
I know that most IDEs will respect the @var annotation, but in this case, for PhpStorm at least, that doesn't seem to stick past the first subsequent use of $this.
For exanple:
class AppServiceProvider
{
public function boot()
{
Relation::macro('setMorphTables', function ($foreignPivotTypeField, $relatedPivotTypeField = null) {
$parentModel = $this->getParent();
$currentTable = $this->getTable()
});
}
}
The code works of course, but when I type the ->, the IDE's auto-fill suggestions are for the AppServiceProvider class, not the Relation class.
If I add /** @var MorphToMany $this */ to override the IDEs assumptions (which works as expected on normal variables), the suggestions are corrected, but only for the first use of $this. The second one reverts back to listing AppServiceProvider options, unless I place that annotation before each use of $this.
So, is there a more proper way to annotate the new definition of $this, or is this just a shortcoming of PhpStorm?