phpphpstormphpdocdocblocks

How to use a $this reference inside PHP docblocks


I have a project that utilised MVC where the view file is inherting $this which refers to a view class attached to the controller.

Helper classes have been attached in some of the views and are used like follows:

<?=$this->someHelper->renderSomething()?>

I was hoping to help devs and the IDE out by doing this:

/** @var SomeHelper $this->someHelper */

It's not supported, seemingly. Is there a way to achieve this?

I can only find a workaround at the moment, to declare the helper as a new variable and include a @var statement for that.


Solution

  • It's not possible, you are supposed to type hint the $this instead. If $this is not any concrete class you can type hint, create a fake class/interface instead which will act as a helper to the IDE:

    // somewhere outside of your code base, but accessible by the IDE
    // use the name of your choice
    interface CodeIgniterMvc
    {
        /**
         * @return string
         */
        function renderSomething(): string;
    
        /**
         * @param array $filter Filtering conditions
         * @return \Your\App\Models\User[]
         */
        function getUsers(array $filter): array;
    }
    

    and in the views:

    /** @var $this CodeIgniterMvc **/
    

    Of course include in the repository so every team member can gain such benefits.