Search code examples
phptraitstype-hintingphpdoc

How to type hint the `$this` property in a trait


I have a trait that that is being used in a class. In that trait, I'd like to be able to type hint which class it is being used.

This trait would most likely be used by that one class only. I only separated its concerns for organization purposes.

class Foo extends Model
{
    use Concerns/HasBar;
}
trait HasBar
{
    public function bar()
    {
        $this->... // Type hint $this to Foo
    }
}

Solution

  • You can use var tag inside your HasBar::bar() method to type hint public members of the class

    trait HasBar
    {
        public function bar()
        {
            /* @var Foo $this */
            $this->... // Type hint $this to Foo
        }
    }