k0pernikus
k0pernikus

Reputation: 66817

How to type hint a property on $this in php?

Assume that in a template.phtml, there is a property someInstance of the class SomeClass defined on $this.

So in the file, one has access to:

$this->someInstance

yet the developer has no immediate clue what type $this->someInstance is.

I know I could typehint on the fly:

<?php

class SomeClass {
    public int $foo;
    public string $bar;
}


$someInstance = $this->someInstance;
/**
 * @var SomeClass $someInstance
 */
$someInstance-> // I have autocompletion here

Screenshot of avaiable autocompletion

Yet is there a way to provide a phpdoc for $this->someInstance directly without going through an extra local variable?

My goal is to add code-documentation to existing files without adding to much refactoring noise.

I tried:

/**
 * @var SomeClass $this->someInstance
 */

and:

/**
 * @var SomeClass $this::someInstance
 */

yet that did not work.

Upvotes: 0

Views: 48

Answers (1)

k0pernikus
k0pernikus

Reputation: 66817

As a workaround you may be able to add classes as documentation for your views, e.g. for your template.phtml, add:

class TemplateView {
    public SomeClass $someInstance;
}

And then you could typehint $this:

/**
 * @var TemplateView $this
 */
$this-> // you have autocomplete here

enter image description here

Upvotes: 1

Related Questions