Search code examples
phpphpstormtraitstype-hinting

Return type 'parent' in php trait methods


What does happen if a trait method declares the return type parent or does use parent as a parameter type?

PhpStorm seems to indicate that parent used in a trait does actually refer to the class implementing the trait which seems strange as static already does exactly this - doesn't it? If it's true that traits declare everything exactly as if the code would have been written in the implementing class, shouldn't parent refer to the actual parent of the implementing class? Does it actually do this (and only the IDE has a misleading type hint)?

trait MyTrait {
    public function doSomething(parent $parent): parent
    {
        return $parent
    }
}

class MyClass extends MyParentClass{
    use MyTrait;
    public function doSomethingElse() {
        $parent = new MyParentClass();
        $this->doSomething($parent);
    }
}

Is $parent (MyParentClass) a valid parameter for $this->doSomethingElse here? Or will this throw a type error, because the trait expects an instance of MyClass?


Solution

  • If you use parent in a trait it referrs to the parent of the class which is using the trait - as expected.

    Testing it in a real world example (yes, I could have done this before...) showed, that everything works as expected: MyTrait::doSomething does expect MyParentClass as parameter and return value. So only the IDE hint (MyClass) is wrong.